How can I update a value of an element of an array without changing the position in React native using useState?

对着背影说爱祢 提交于 2021-01-29 08:08:26

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!