从对象数组中删除对象的元素 - 反应状态

时间:2018-06-07 02:38:11

标签: javascript reactjs ecmascript-6

我有一个使用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);

1 个答案:

答案 0 :(得分:2)

您应该创建一个新数组,然后将其设置为该状态中people的新值。其中一种方法是使用Array.prototype.map函数。

  

map()方法创建一个新数组,其中包含调用a的结果   为调用数组中的每个元素提供了函数。

例如,您可以这样做:

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),
            }
        }
    });
});

我设置了一个代码盒来为您演示这个。请查看here

相关问题