如何在React中正确更改对象的多个嵌套数组的状态?

时间:2019-05-29 23:03:25

标签: javascript reactjs react-native setstate

在React中更改多个嵌套对象数组状态的最佳方法是什么?让我们看下面的示例:我有一个组件,将显示每种类型的顶部播放列表。我有一个属性 genre ,它是一个对象数组,每个对象都有一个属性 songs ,它也是一个对象数组。如果我想将名为Fortune of Fortune的歌曲及时更改为Child(让我们假设Change函数作为参数,我已经从UI更改中提供了Song和Genre的索引)。如何访问嵌套对象的多个级别而不改变状态?

this.state = {
    title: 'Top playlists',
    genres: [
      {
        genreName: 'pop',
        followers: 2456,
        songs: [
          {
            title: 'Soldier of fortune',
            author: 'Deep Purple',
          },
        ],
      },
    ],
  };

handleChangeSongName = (e, genreIndex, songIndex) => {
    // genreIndex = 0;
    // songIndex = 0;
    // e.target.name = title;
    // e.target.value = "Child in time"  
    ...What to do here?
  }

2 个答案:

答案 0 :(得分:1)

您可以将handleChangeSongName函数修改为此:

  handleChangeSongName = (e, genreIndex, songIndex) => {
// genreIndex = 0;
// songIndex = 0;
// e.target.name = title;
// e.target.value = "Child in time"  
this.setState((prevState) => {
  let temp = {
    ...prevState,
    genres: [...prevState.genres]
  }

  // change title "Soldier of fortune" to "Child in time"
  temp.genres[genreIndex].songs[songIndex][e.target.name] = e.target.value

  return temp
})

}

答案 1 :(得分:0)

我会这样更改您的状态:

this.state = {
      title: "Top playlists",
      genres: [
        {
          followers: 2456,
          genreName: "pop",
          songs: [
            {
              title: "Soldier of fortune",
              author: "Deep Purple"
            }
          ]
        }
      ]
    };

然后

handleChangeSongName = (e, genreIndex, songIndex) => {
    // genreIndex = 0;
    // songIndex = 0;
    // e.target.name = title;
    // e.target.value = "Child in time"  
    ...What to do here?

    const genres = _.cloneDeep(this.state.genres); // create deep copy with underscore
    // or like this
    // const genres = JSON.parse(JSON.stringify(this.state.genres))

    if(genres.length && genres[genreIndex] && genres[genreIndex].songs.length && genres[genreIndex].songs[songIndex]) {
        genres[genreIndex].songs[songIndex][e.target.name] = e.target.value;

        this.setState({
            genres: genres
        });
     }

  }