let [_value, setValue] = useState([1, 2, 3, 4, 5, 1, 2, 3, 4, 5 ]);
在这段代码中,如果我想更改 _value[3] 如何使用 setValue 更改值?
在我的项目中,我必须在单击(评分)按钮时更改 _value[index]。
所以我必须动态改变 _value[index]。
如果你知道答案,请告诉我。谢谢!
最佳答案
通常有几种方法可以在 JavaScript 中更新数组。重要的是,无论您做什么,您都希望确保不会改变现有状态。
一种方法是制作数组的浅拷贝,对拷贝进行变异,然后设置新状态:
function update(index, newValue) {
// shallow copy
const newArray = [..._value];
// mutate copy
newArray[index] = newValue;
// set state
setValue(newArray);
}
另一种选择是对数组进行map
,当索引与所需索引匹配时返回新值。
function update(index, newValue) {
const newArray = _value.map((v, i) => {
if (i === index) return newValue;
return v;
});
setValue(newArray);
}
关于javascript - 在 React Hook 中,如何更改 useState 数组的特定值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67781239/