我有一个使用 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功能。
The map() method creates a new array with the results of calling a provided function on every element in the calling array.
例如,您可以这样做:
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),
}
}
});
});
我设置了一个 codesandbox 来为您演示这一点。看看here .
关于javascript - 从对象数组中删除对象的元素 - react 状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50732216/