简体   繁体   English

React Hooks:如何更新 state 中的嵌套数组属性?

[英]React Hooks: How to update a nested array property in a state?

I have a state of arrays. The array has an array nested inside it.我有一个 arrays 的 state。数组中嵌套了一个数组。 This is what my state looks like:这是我的 state 的样子:

const [record, setRecord] = useState([
    {
        name: "Pink Floyd",
        rank: 1,
        songs: [
            {
                name: "A",
                year: "1970",
                downloads: "10",
            },
            {
                name: "B",
                year: "1980",
                downloads: "20",
            },
            {
                name: "C",
                year: "1990",
                downloads: "5",
            },
        ],
    },
    {
        name: "Led Zeppelin",
        rank: 2,
        songs: [
            {
                name: "D",
                year: "1965",
                downloads: "25",
            },
            {
                name: "E",
                year: "1975",
                downloads: "65",
            },
            {
                name: "F",
                year: "1985",
                downloads: "90",
            },
        ],
    },
]);

I am able to update the rank property by doing this:我可以通过这样做来更新 rank 属性:


setRecord(prevRecord =>
    prevRecord.map((el) =>
        el.name == "someName" ? { ...el, rank: "someRank" } : el
    )
);

Now, I want to update the 'downloads' property which is nested inside songs.现在,我想更新嵌套在歌曲中的“下载”属性。 How can I update the downloads property?如何更新下载属性?

you must iterate through your state and look for item you want to change您必须遍历 state 并查找要更改的项目

  const newState = record.map((item) => {
    if (item.name === 'YOUR_DESIRE_NAME_TO_MODIFY') {
      const newSongs = item.songs.map((song) => {
        if (song.name === 'DESIRE_SONG_NAME_TO_MODIFY') {
          song.downloads = '100'
        }
        return song
      })
      item.songs = newSongs
    }
    return item
  })

  setRecord(newState)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM