简体   繁体   中英

Updating a value in a React state array

I'm trying to update a very simple state array.

Here's how I am initializing the array.

const [total, setTotal] = useState([0,0,0]);

I also have an index to keep track of called, option

To make it simple, I just need a function that takes in 'price' as an argument and adds it to the state array named 'total'

const addToTotal = (price) => {setTotal(total[option] += price)}

I know I have to use the spread operator to update and that this is incorrect, but I hope this gives an idea of what I'm trying to do.

Edit: Sorry that there is a little confusion. When I said 'add', I want to increment the number in that specific array.

If option = 1 then I 'add' 1 it, the result should be [1, 0, 0]

Use the callback in usestate set method

  const addToTotal = (price) => {
    setTotal(prev => {
     prev[option] += price
     return prev
    }
  )}

One way of doing it is by using map to update the state

const addToTotal = (price) => {
    const newState = total.map((t, i) => i === option ? t + price : t)
    setTotal(newState)
)}

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