How to dynamically add values to an array in React?

In React, we can utilize the useState hook to create an array that contains dynamic values, and use the setArray function to update the values of the array.

Here is a simple example demonstrating how to add new values to an array.

import React, { useState } from 'react';

function App() {
  const [array, setArray] = useState([]);

  const addItem = () => {
    // 创建一个新数组,将旧数组的值和新值合并
    const newArray = [...array, '新值'];
    setArray(newArray);
  };

  return (
    <div>
      <button onClick={addItem}>添加新值</button>
      <ul>
        {/* 遍历数组,渲染列表 */}
        {array.map((item, index) => (
          <li key={index}>{item}</li>
        ))}
      </ul>
    </div>
  );
}

export default App;

In the example above, we use useState to create an array state named array and initialize it as an empty array. Next, we define an addItem function that is called when a button is clicked. The addItem function first creates a new array newArray by merging the values of the old array and the new value. Finally, we use setArray to update the state array to newArray.

In rendering components, we use the map method to iterate through an array and render a list with each item in the array. The key property needs to be set to a unique value. Here we use the index as the key, but it is better to use a unique id in actual applications.

When the button is clicked, the addItem function is called to add a new value to the array and update the view by re-rendering the component.

bannerAds