[英]Remove element of an object from array of objects - react state
我有一个使用React存储在状态中的对象数组
this.state= {
people: [
{
name: 'Tom',
hobbies: ['dancing', 'swimming']
}, {
name: 'Dean',
hobbies: ['playing', 'wondering']
}, {
name: 'Jack',
hobbies: ['shooting', 'hiking']
}, {
name: 'Natalie',
hobbies: ['rock', 'cats']
}
]
};
我想通过从业余爱好中删除一个特定元素来更新状态。 我试图从状态复制人员数组,然后遍历每个人对象然后遍历每个爱好数组,然后检查该元素是否是我要删除的元素,但我没有设法删除它,状态没有改变。 我试过的是映射它然后过滤。
什么是最简单,最快速的方法? 我刚开始学习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
的新值。 其中一种方法是使用Array.prototype.map函数。
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),
}
}
});
});
我制作了一个代码盒来为你演示这个。 在这里查看 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.