Why not to use splice with spread operator to remove item from an array in react?

馋奶兔 提交于 2021-02-20 19:11:45

问题


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 });
}

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?


回答1:


filter() has a more functional approach, which has its benefits. Working with immutable data is much more easier, concurrency and error safe.

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];

Creates a copy of this.state.items, thus it will not mutate them once you do a splice().

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.




回答2:


 const items = [...this.state.items]; // spread
 const mutatedItems = this.state.items.filter(() => {}) // filter

they are the same.
although i found spread line is confusing, and less intuitive than filter.

but i prefer destructuring:

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

why? because sometimes within a function/method i have other destructuring assignment such

  const { modalVisible, user } = this.state

So i think why not destructure item as well there. For some who writes a lot of codes in multiple codebase, it would help a lot to work on on "how accurate, and fast can this code skimmed?" as i myself dont really remember what i wrote last week.
While using spread would make me write more lines and doesnt help me when re-read it next month.



来源:https://stackoverflow.com/questions/58351957/why-not-to-use-splice-with-spread-operator-to-remove-item-from-an-array-in-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!