【问题标题】:React Hooks: How to update a nested array property in a state?React Hooks:如何更新状态中的嵌套数组属性?
【发布时间】:2023-01-31 20:46:53
【问题描述】:

我有一个数组状态。该数组内部嵌套了一个数组。这就是我的状态:

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

我可以通过这样做来更新排名属性:


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

现在,我想更新嵌套在歌曲中的“下载”属性。如何更新下载属性?

【问题讨论】:

  • { ...el, rank: "someRank" , songs: el.songs.map(song => ({ ...song, downloads: 10 }))}

标签: javascript reactjs arrays react-hooks react-functional-component


【解决方案1】:

你必须遍历你的状态并寻找你想要改变的项目

  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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-19
    • 2020-01-16
    • 1970-01-01
    • 2019-01-28
    • 2020-12-04
    • 1970-01-01
    • 2021-06-04
    • 1970-01-01
    相关资源
    最近更新 更多