不同于this post ,我不想在数组中添加新项目,但我想修改索引 i
处的项目。
除了像那样深度克隆整个阵列之外,还有其他解决方案吗?
const oldList = this.state.list;
let newList = JSON.parse(JSON.stringify(oldList));
newList[i] = "foo";
this.setState({list: newList});
感谢您的帮助。
最佳答案
您可以使用点差。
const oldList = this.state.list;
let newList = [...oldList];
newList[i] = "foo";
this.setState({ .list: newList });
但如果数组的元素是对象,则传播将不起作用。因为它只会制作引用旧对象的数组的新副本。但在你的情况下,你分配字符串。所以它是原始类型。
So if I'm correct, the spread operator will basically do a deep-cloning
Spread 进行浅克隆。认为 array spread
与创建新数组相同,并将所有旧值复制到新数组
a = [...b];
与
相同a = [];
for(let i = 0; i < b.length; i++) a.push(b[i]);
because Vue overrides mutation methods on arrays like push(...)
对于推送,也可以使用spread
a = [...b, 'new item'];
对于pop,可以使用splice
a = b.slice(-1, 1);
关于javascript - 正确更新状态数组中给定索引处的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54622592/