簡體   English   中英

從對象數組中刪除對象的元素 - 反應狀態

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM