从一个对象数组中删除对象的元素 - React状态

3
我使用React将对象数组存储在状态中。
this.state= {
  people: [
    {
      name: 'Tom',
      hobbies: ['dancing', 'swimming']
    }, {
      name: 'Dean',
      hobbies: ['playing', 'wondering']
    }, {
      name: 'Jack',
      hobbies: ['shooting', 'hiking']
    }, {
      name: 'Natalie',
      hobbies: ['rock', 'cats']
    }
  ]
};

我想通过从爱好中删除一个特定的元素来更新状态。 我尝试从状态中复制people数组,然后迭代每个人对象,然后通过每个爱好数组检查元素是否是我想要删除的元素,但我没有成功删除它,状态没有改变。 我尝试过的方法是先映射再过滤。
有什么最简单和最快的方法吗? 我刚开始学习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);

应该是“人员”,而不是“教练”。 - Ninja
刚刚修好了,发帖前忘记检查超时时间了 :P - user9254191
你可以使用 .pop() 或 .splice() 方法,这里有相关文档:https://www.w3schools.com/Jsref/jsref_splice.asp - Ninja
如果你想做得正确,就不应该直接改变你的状态。你是想用索引来做这个还是只是举个例子?你能用值来举例吗? - devserkan
1个回答

2
您应该创建一个新数组,然后将其设置为状态中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),
            }
        }
    });
});

我创建了一个 CodeSandbox 来为您演示。请点击这里查看。

好的回答。我建议在这里使用回调函数来设置状态。 - devserkan
是的,这正是我自己无法做到的:D 太好了,现在我明白了发生了什么以及如何做!非常感谢你:) - user9254191

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接