不,这是不可取的。您有用于更新状态的 useState 第二个数组元素 (setObjArray)。阅读 React useState 的文档。有两种基本方法,但没有太大区别。第一种方法;
const changeName = (id, newName) => {
// map through the array and change the name of the element with the id you are targeting
const changedArr = objArray.map((element) => {
if (element.id === id) {
return {
...element,
name: newName,
};
} else {
return element;
}
});
// set the returned array as you new state
setObjArray(changedArr)
};
第二种方法;
- 您可以访问以前的状态。这样您就可以对以前的状态进行更改并将新数组作为新状态返回。
const newChangeName = (id, newName) => {
setObjArray((prev) => {
// map through the array and change the name of the element with the id you are targeting
// set the returned array as you new state
return prev.map((element) => {
if (element.id === id) {
return {
...element,
name: newName,
};
} else {
return element;
}
});
});
};
希望这有所帮助。