【发布时间】:2019-06-22 04:42:24
【问题描述】:
我正在学习 React,在其中一个答案中,我看到在从数组中删除项目时正在使用 splice 方法。 链接到解决方案: Delete item from state array in react
要从数组中删除一个元素,只需这样做:
array.splice(index, 1); 在你的情况下:
removePeople(e) {
var array = [...this.state.people]; // make a separate copy of the array
var index = array.indexOf(e.target.value)
if (index !== -1) {
array.splice(index, 1);
this.setState({people: array});
}
},
预期:与许多其他博客一样,我们使用过滤器方法从列表中删除项目。 为什么答案越来越受欢迎,而我们在这里没有使用过滤器方法?
【问题讨论】:
-
你的问题是什么,为什么使用拼接而不是过滤器?
-
filter 比 splice 更好,因为 filter 不会改变数组。正如您在答案列表中看到的那样,过滤方法获得了更多的赞成票,但接受的答案取决于提出问题的人。