从状态数组中删除项目

JavaScript

小宇宙前端

2020-03-12

故事是,我应该能够将鲍勃,莎莉和杰克放进盒子里。我也可以从包装盒中取出。卸下后,将不留任何插槽。

people = ["Bob", "Sally", "Jack"]

我现在需要删除“ Bob”。新的数组将是:

["Sally", "Jack"]

这是我的react组件:

...

getInitialState: function() {
  return{
    people: [],
  }
},

selectPeople(e){
  this.setState({people: this.state.people.concat([e.target.value])})
},

removePeople(e){
  var array = this.state.people;
  var index = array.indexOf(e.target.value); // Let's say it's Bob.
  delete array[index];
},

...

在这里,我向您展示了最少的代码,因为它包含更多内容(onClick等)。关键部分是从数组中删除,删除,销毁“ Bob”,但removePeople()在调用时不起作用。有任何想法吗?我一直在看这个,但由于使用React,所以我可能做错了。

第992篇《从状态数组中删除项目》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

5个回答
Harry宝儿 2020.03.12

首先定义一个值非常简单

state = {
  checked_Array: []
}

现在,

fun(index) {
  var checked = this.state.checked_Array;
  var values = checked.indexOf(index)
  checked.splice(values, 1);
  this.setState({checked_Array: checked});
  console.log(this.state.checked_Array)
}
小胖Gil 2020.03.12

提到了一些使用“拼接”的答案,就像史密斯·史密斯所说的那样,对阵列进行了突变。我建议您使用方法调用“ slice” (此处为“ slice”的文档)来复制原始数组。

JinJin樱 2020.03.12

使用React时,切勿直接改变状态。如果Array更改了一个对象(或,它也是一个对象),则应创建一个新副本。

其他人建议使用Array.prototype.splice(),但是该方法会使Array发生变化,因此最好不要splice()与React 一起使用

最容易用于Array.prototype.filter()创建新数组:

removePeople(e) {
    this.setState({people: this.state.people.filter(function(person) { 
        return person !== e.target.value 
    })});
}
西里阿飞 2020.03.12

这是亚历山大·彼得罗夫(Alexandre Petrov)使用ES6的响应的一个小变化

removePeople(e) {
    let filteredArray = this.state.people.filter(item => item !== e.target.value)
    this.setState({people: filteredArray});
}
猪猪理查德 2020.03.12

要从数组中删除元素,只需执行以下操作:

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

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android