如何在不使用useState更改React native中的位置的情况下更新数组元素的值



如何在不修改数组位置的情况下使用useState更改数组的特定值。例如:如果我不使用useState,我可以这样修改数组:checkBox[2] = true。我试过setCheckBox[2](true),但它确实有效。

有人能帮我解决这个问题吗。

const [checkBox, setCheckBox] = useState(
[true, false, false, false, false, false, false, false]
);

如何在不更改位置的情况下将此数组的索引2中的值更改为true?

我认为你可以简单地进行

const myFunction = () => {
let arrayCopy = [...checkBox]   // or Array.from() in order to avoid reference
arrayCopy[2] = true
setCheckBox(arrayCopy)
}

像这样你跳过循环。。。

setCheckBox[2](true)-这将不起作用,因为setCheckBox是一个函数,而不是数组或对象文字。setCheckBox[2]在这里使用的语法是错误的。

您需要避免直接更改数组。这样做不会触发组件的重新渲染。

为了正确更新状态,在您的情况下,可以使用.map()方法转换checkBox数组的值。.map()方法将返回一个新数组,该数组将包含转换后的值。

// 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);

相关内容

最新更新