我在更新数组中的对象时遇到问题。
const [list, setList] = useState([]);
const changeRecordIndex = list.findIndex((recordItem) => recordItem.id === recordID);
我创建新数组,复制我需要的对象,然后更改对象的一个参数。看上去棒极了!但在这种情况下,我的最终数组有问题 - 我有 2 个类似的对象,它们具有不同的参数,我想更改它们。
setList([...list, { ...list[changeRecordIndex], taskText: liItem.innerText }]);
在这种情况下一切都好
const newArr = [...list];
newArr[changeRecordIndex] = { ...newArr[changeRecordIndex], taskText: liItem.innerText };
setList(newArr);
第一个案例有什么问题?
第一种方法的问题在于,您将更新的对象添加到数组中,而不删除旧的对象,因此最终得到两个对象:原始对象和更新后的对象。
在你的第一种情况下:
setList([...list, { ...list[changeRecordIndex], taskText: liItem.innerText }]);
这会添加列表中的所有现有项目,包括您尝试更新的项目,然后将更新的对象添加到末尾。这会创建一个副本。 正确做法(第二种情况):
const newArr = [...list]; // Copy the array
newArr[changeRecordIndex] = { ...newArr[changeRecordIndex], taskText: liItem.innerText }; // Update the object
setList(newArr); // Set the updated array
在这种方法中,您将替换数组中的对象而不重复它。坚持使用第二种方法以避免重复!