从状态数组删除项目的反应 [英] Delete item from state array in react
问题描述
这个故事是,我应该能够把鲍勃,莎莉和杰克成箱。我也可以从包装盒中取出。取出时,没有插槽离开了。
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"]
我现在需要删除,说,鲍勃。新的数组将是:
I now need to remove, say, "Bob". The new array would be:
["Sally", "Jack"]
下面是我反应过来组件:
Here is my react component:
...
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];
},
...
在这里,我告诉你一个最小的code作为有更多的给它(的onClick等)。关键部分是从数组中删除,排除,销毁鲍勃,但 removePeople()
调用时不能正常工作。有任何想法吗?我是<一个href=\"http://stackoverflow.com/questions/5767325/remove-a-particular-element-from-an-array-in-javascript\">looking在这个但我可能因为我使用的反应而做错事。
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;
var index = array.indexOf(e.target.value)
array.splice(index, 1);
this.setState({people: array });
},
这篇关于从状态数组删除项目的反应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!