Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
618 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...