问题
How can I change a specific value of an array using useState without modifying it's position. For example: if I wouldn't use useState, I can modify the array like this: checkBox[2] = true. I tried setCheckBox[2](true) but it does work.
Can anyone help me with this issue.
const [checkBox, setCheckBox] = useState(
[true, false, false, false, false, false, false, false]
);
how can I change the value in index 2 of this array to true without changing the position?
回答1:
setCheckBox[2](true) - this will not work because setCheckBox is a function, not an array or an object literal. setCheckBox[2] is just wrong syntax to use here.
You need to avoid mutating the array directly. Doing this will not trigger a re-render of your component.
To update the state correctly, in your case, you can use .map() method to transform the values of the checkBox array. .map() method will return a new array that will contain the transformed values.
// if index is equal to two, return true, otherwise return the value as it is
const updatedArr = checkBox.map((val, idx) => idx === 2 ? true : val);
// pass the new array to state updater function
setCheckbBox(updatedArr);
来源:https://stackoverflow.com/questions/65393696/how-can-i-update-a-value-of-an-element-of-an-array-without-changing-the-position