如何从状态数组中删除一个项目? [英] How to delete an item from state array?

查看:21
本文介绍了如何从状态数组中删除一个项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

故事是,我应该能够将鲍勃、莎莉和杰克放入一个盒子里.我也可以从盒子中取出.移除后,没有留下任何插槽.

The story is, I should be able to put Bob, Sally and Jack into a box. I can also remove either from the box. When removed, no slot is left.

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

我现在需要删除,比如Bob".新数组将是:

I now need to remove, say, "Bob". The new array would be:

["Sally", "Jack"]

这是我的反应组件:

...

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,所以出了点问题.

Here I show you a minimal code as there is more to it (onClick etc). The key part is to delete, remove, destroy "Bob" from the array but removePeople() is not working when called. Any ideas? I was looking at this but I might be doing something wrong since I'm using React.

推荐答案

要从数组中删除元素,只需:

To remove an element from an array, just do:

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

这篇关于如何从状态数组中删除一个项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆