【问题标题】:Why not to use splice with spread operator to remove item from an array in react?为什么不使用 splice 和扩展运算符从反应数组中删除项目?
【发布时间】:2020-02-09 14:43:09
【问题描述】:

splice() 会改变原始数组,应避免使用。相反,一个不错的选择是使用filter(),它会创建一个新数组,因此不会改变状态。但我曾经使用 splice() 和扩展运算符从数组中删除项目。

removeItem = index => {
  const items = [...this.state.items];
  items.splice(index, 1);

  this.setState({ items });
}

所以在这种情况下,当我记录 items 更改但 this.state.items 保持不变时。 问题是,为什么每个人都使用filter 而不是splicespread?有什么缺点吗?

【问题讨论】:

标签: javascript arrays reactjs immutability


【解决方案1】:

filter() 有一个更实用的方法,它有它的好处。使用不可变数据更加容易,并发和错误安全。

但在您的示例中,您正在通过创建 items 数组来做类似的事情。所以你仍然没有改变任何现有的数组。


const items = [...this.state.items];

创建this.state.items 的副本,因此一旦您执行splice(),它就不会改变它们。

所以考虑到你的做法,它与filter() 没有什么不同,所以现在归结为一个品味问题。

const items = [...this.state.items];
items.splice(index, 1);

VS

this.state.items.filter(i => ...);

还可以考虑性能。以test 为例。

【讨论】:

  • 是的,取决于你的环境,你的测试等等。但我不会担心这一点,因为它在浏览器中运行。如果它是每秒处理数百个请求的服务器调用,那么我会优先考虑性能,否则不会。使用最可维护的代码。
【解决方案2】:
 const items = [...this.state.items]; // spread
 const mutatedItems = this.state.items.filter(() => {}) // filter

它们是相同的。
虽然我发现扩展线令人困惑,而且不如过滤器直观。

但我更喜欢解构:

 const { items } = this.state // destructure
 item.splice()

为什么?因为有时在函数/方法中我有其他解构赋值,例如

  const { modalVisible, user } = this.state

所以我想为什么不在那里解构item。 对于一些在多个代码库中编写大量代码的人来说,研究“这段代码浏览的准确度和速度有多快?”会很有帮助。因为我自己真的不记得我上周写了什么。
虽然使用 spread 会让我写更多的行,并且在下个月重新阅读时对我没有帮助。

【讨论】:

  • 在您的示例中,您正在更改 state 而无需通过 setState()
  • 但是这个方法改变了this.state
  • 解构仍将保持对items 的相同引用,并在您更改items 时发生变异
  • 哦,对不起,我认为只有当它是一个对象时它才会保持引用。
猜你喜欢
  • 1970-01-01
  • 2019-01-15
  • 1970-01-01
  • 1970-01-01
  • 2020-12-20
  • 2021-04-19
  • 2019-09-06
  • 2019-10-27
  • 2022-07-06
相关资源
最近更新 更多