简体   繁体   中英

Updating multiple array object values with useState in React

Feels like I'm frustratingly close to solving this, but not sure how to update all of the values in a given object array with useState. Here's an example:

    const [data, setData] = useState([
       {key: 1,
        value: 25},
       {key: 2,
        value: 30}
        ])

And then assume on a button click I want to add 10 to the value of every item in the array:

    const handleClick = () => {

    const newData = data.map(item => item.value + 10)

     setData ([
         ...data, ???

     ])

newData delivers an updated array, but I'm not sure how to use the Hook to update the state. Thanks!

You can make use of functional state updater and return the mapped result. Also note that since each value is an object you must clone and update just the value field

 const handleClick = () => {
     setData (prevData => data.map(item => ({...item, value: item.value+10})));
}

To put it in your way, it would be like

const handleClick = () => {

    const newData = data.map(item => { 
          return {...item, value: item.value + 10}
    });

     setData(newData);
}

You should setData to the result of your map iteration. It should be something like this:

const handleClick = () => {

   const newData = data.map(item => item.value + 10)

   setData(newData)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM