Javascript 从对象数组中删除对象的元素-反应状态
我有一个使用React以状态存储的对象数组Javascript 从对象数组中删除对象的元素-反应状态,javascript,reactjs,ecmascript-6,Javascript,Reactjs,Ecmascript 6,我有一个使用React以状态存储的对象数组 this.state= { people: [ { name: 'Tom', hobbies: ['dancing', 'swimming'] }, { name: 'Dean', hobbies: ['playing', 'wondering'] }, { name: 'Jack', hobbies: ['shooting', 'hiking']
this.state= {
people: [
{
name: 'Tom',
hobbies: ['dancing', 'swimming']
}, {
name: 'Dean',
hobbies: ['playing', 'wondering']
}, {
name: 'Jack',
hobbies: ['shooting', 'hiking']
}, {
name: 'Natalie',
hobbies: ['rock', 'cats']
}
]
};
我想通过从嗜好中删除一个特定元素来更新状态。
我试图从state复制people数组,然后遍历每个person对象,然后遍历每个嗜好数组,然后检查元素是否是我要删除的元素,但我没有成功删除它,state没有更改。
我尝试的是映射它,然后过滤
最简单和最快的方法是什么?
我刚开始学习React,所以我想用setTimeout来做
目前我只有从随机人中选择随机爱好的代码
setTimeout(() => {
const randInst = Math.floor(Math.random() * this.state.people.length);
const hobbyIndex = Math.floor(Math.random() * this.state.people[randInst].hobbies.length);
}, 500);
您应该创建一个新数组,然后将其设置为处于该状态的
people
的新值。方法之一是使用函数
map()方法使用调用
在调用数组中的每个元素上提供函数
例如,您可以这样做:
const randomPersonIndex = Math.floor(Math.random() * this.state.people.length);
const randomHobbyIndex = Math.floor(Math.random() * this.state.people[randomPersonIndex].hobbies.length);
this.setState({
people: this.state.people.map((person, index) => {
if (randomPersonIndex !== index) {
return person; // not person we are targeting, don't change it
} else {
return {
...person,
hobbies: person.hobbies.filter((v, i) => i !== randomHobbyIndex),
}
}
});
});
我制作了一个代码沙盒来为您演示这一点。查看它。应该是“人”而不是“讲师”,只是修复了它,在发布之前忘记查看超时:Pyou可以使用.pop()或.splice()方法,herehttps://www.w3schools.com/Jsref/jsref_splice.aspIf 如果你想正确地做到这一点,你不应该直接改变你的状态。你是想用索引来准确地描述这一点,还是仅仅是一个例子?你能用值作为例子吗?回答得好。我只建议在这里使用setState的回调函数。是的,这正是我自己无法做到的:D太好了,现在我知道发生了什么以及如何做了!非常感谢男士:)