javascript - 从对象数组中删除对象的元素 - react 状态

标签 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);

最佳答案

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

相关文章:

javascript - 为什么订阅没有被调用

javascript - JSSOR - 每次网页刷新后保持当前 slider 位置

javascript - 向一些 javascript 按钮添加一个类

javascript - 从对象数组中获取唯一元素

javascript - 切换数组中的项目 react

javascript - 在按钮上单击交换正在使用 "document.createElement(' 脚本加载的 JS 文件')

javascript - 代码片段以及箭头函数和普通函数的行为

javascript - 来自对象等于对象的 Mocha chai 意外断言测试错误

javascript - 在页面上多次使用的 react 组件上动态渲染唯一的按钮

Facebook React 的 typescript