问题描述
splice()更改原始数组,应避免使用.相反,一个不错的选择是使用 filter()会创建一个新数组,因此不会使状态发生变化.但是我曾经使用splice()和传播运算符从数组中删除项目.
splice() mutates the original array and should be avoided. Instead, one good option is to use filter() which creates a new array so does not mutates the state. But I used to remove items from an array using splice() with spread operator.
removeItem = index => {
const items = [...this.state.items];
items.splice(index, 1);
this.setState({ items });
}
因此,在这种情况下,当我登录 items
更改但 this.state.items
保持不变时.问题是,为什么每个人都使用 filter
而不是带有 spread
的 splice
?有什么缺点吗?
So in this case when I log items
changes but this.state.items
stays unchanged.Question is, why does everyone use filter
instead of splice
with spread
? Does it have any cons?
推荐答案
filter()
具有更实用的方法,它有其优点.处理不可变数据更加容易,并发和错误安全.
filter()
has a more functional approach, which has its benefits. Working with immutable data is much more easier, concurrency and error safe.
但是在您的示例中,您正在通过创建 items
数组来做类似的事情.因此,您仍然不会更改任何现有数组.
But in your example, you are doing something similar by creating the items
array. So you are still not mutating any existing arrays.
const items = [...this.state.items];
创建 this.state.items
的副本,因此一旦执行 splice()
,它将不会使它们变异.
Creates a copy of this.state.items
, thus it will not mutate them once you do a splice()
.
因此,考虑到您使用的方法,它与 filter()
没什么不同,因此现在归结为一个趣味性.
So considering you approach, it is no different than filter()
, so now it just boils down to a matter of taste.
const items = [...this.state.items];
items.splice(index, 1);
VS
this.state.items.filter(i => ...);
也可以考虑性能.例如,请检查此测试.
Also performance may be taken into consideration. Check this test for example.
这篇关于为什么不使用带有spread运算符的splice从react中的数组中删除项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!