为什么不使用带有扩展运算符的 splice 从数组中删除项目以进行反应? [英] Why not to use splice with spread operator to remove item from an array in react?

查看:45
本文介绍了为什么不使用带有扩展运算符的 splice 从数组中删除项目以进行反应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 而不是 splicespread?它有什么缺点吗?

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 => ...);

还可以考虑性能.例如,检查这个 test.

Also performance may be taken into consideration. Check this test for example.

这篇关于为什么不使用带有扩展运算符的 splice 从数组中删除项目以进行反应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆