How to dynamically add values to an array in React?

In React, we can use the setState method to dynamically add values to an array. Here is an example:

import React, { useState } from 'react';

function App() {
  const [items, setItems] = useState([]);

  const addItem = () => {
    setItems(prevItems => [...prevItems, 'new item']);
  };

  return (
    <div>
      <button onClick={addItem}>添加项</button>
      <ul>
        {items.map((item, index) => (
          <li key={index}>{item}</li>
        ))}
      </ul>
    </div>
  );
}

export default App;

In the above example, we first use the useState hook to create an array called items and a function called setItems. Next, we define an addItem function that updates the state of the items array by using a function in setItems. We add the new item to the previous array of items by using the spread operator.

Finally, we used the items.map method in the rendering section of the component to iterate through the items array and add something to each item.

  • Elements. It should be noted that we have in each.
  • A unique key attribute is used on elements so that React can properly identify updates to each element.
  • bannerAds