简体   繁体   中英

Update a specific variable of a useState array (by its place) in React.js?

In my React.js functional component, I need to update only one of the variable of a useState array :

let [nums, setNums] = React.useState([0,0,0])

to this:

let [nums, setNums] = React.useState([0,1,0])

without changing the other variables (something like: setNums(nums[1] = 1) ).

Is that possible?

Thanks!

Maybe use index of the element in the array.

const handleChange = (targetIndex)=>{
setState(nums.map(element, index) => if(targetIndex === index){ return updated;} return element);
}

You can create a shallow copy using spread syntax and set new value using index on the copied array:

const update = (index, value) => {
  const copy = [...nums]  // Create a copy
  copy[index] = value     // Set new value
  setNums(copy)
}

Note that above method is not mutating the original data. A demo:

 const nums = [0, 0, 0] const copy = [...nums] copy[1] = 100 console.log(nums, copy)

PS: Using map() function is not really required in this case because we already know which index value should be updated.

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