如何在useState
不修改数组位置的情况下使用它来更改数组的特定值。例如:如果我不使用useState
,我可以像这样修改数组:checkBox[2] = true
。我试过了,setCheckBox[2](true)
但是确实可以。
谁能帮我解决这个问题。
const [checkBox, setCheckBox] = useState(
[true, false, false, false, false, false, false, false]
);
如何在不更改位置的情况下将该数组的索引2中的值更改为true?
setCheckBox[2](true)
-这setCheckBox
是不起作用的,因为它是一个函数,而不是数组或对象文字。setCheckBox[2]
在这里使用错误的语法。
您需要避免直接更改数组。这样做不会触发组件的重新渲染。
若要正确更新状态,您可以使用.map()
方法来转换checkBox
数组的值。.map()
方法将返回一个新数组,其中包含转换后的值。
// if index is equal to 2, 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);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句