而不是使用
.find
,使用
.findIndex
首先,这样就可以用新对象替换数组中的对象。(记住不要使用
Object.assign
在React中,当第一个参数是stateful时,因为这会导致状态突变)
在尝试更新之前,还应该首先检查所有这些对象是否存在。
if (!formValues.constructionSet || !values || !values.opaqueMaterial) {
return;
}
const newMat = values.opaqueMaterial;
const index = addedOpaqueMaterials.findIndex(mat => mat.id === newMat.id);
if (index === -1) {
// Add to the end of the existing array:
const newOpaqueMaterials = [
...addedOpaqueMaterials,
newMat
];
// put newOpaqueMaterials into state
} else {
// Replace the object in the state array with the new object:
const newOpaqueMaterials = [
...addedOpaqueMaterials.slice(0, index),
newMat,
...addedOpaqueMaterials.slice(index + 1)
];
// put newOpaqueMaterials into state
}