javascript - 正确更新状态数组中给定索引处的项目

标签 javascript arrays reactjs

不同于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/

相关文章:

javascript - 过滤器必须显示默认组

javascript - Webpack 无法从 node_modules 加载包

javascript - 加载新数据时c3 JS滚动条跳转

javascript - 是否可以使用包含多个单词的字符串作为 json key?

Javascript:用另一组项目替换数组中的项目

arrays - 如何将两个(或更多)tableView 单元格添加在一起以制作 'total'

javascript - React 中的 Axios AJAX 调用仅返回初始状态

java - 使用数组 Java 更新值后循环遍历 ArrayList

node.js - 30 天后自动删除 MongoDB 文档

javascript - ReactJs——在 li 元素的点击事件上,类不会立即添加