如何在不使用 useState 更改 React Native 中的位置的情况下更新数组元素的值? [英] How can I update a value of an element of an array without changing the position in React native using useState?

查看:103
本文介绍了如何在不使用 useState 更改 React Native 中的位置的情况下更新数组元素的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

how can I change the value in index 2 of this array to true without changing the position?

推荐答案

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

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.

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

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

这篇关于如何在不使用 useState 更改 React Native 中的位置的情况下更新数组元素的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆