【问题标题】:How to setState for nested array of object in react?如何在反应中为嵌套的对象数组设置状态?
【发布时间】:2021-08-27 14:15:09
【问题描述】:

这是对象,假设我要在列表中添加一些内容:[],我该怎么做?我知道我们可以使用 prevList 回调来做到这一点,但我对映射它有点困惑。

const [boardlist, setBoardlist] = useState([
    {
      id: 1,
      boardName: "home work",
      data: [
        {
          id: 1,
          header: "Stuff to do",
          list: [
            {
              id: 1,
              taskTitle: "working from home",
            },
          ],
        },
        {
          id: 2,
          header: "In Progress",
          list: [],
        },
        {
          id: 3,
          header: "Done",
          list: [],
        },
      ],
    },
  ]);

【问题讨论】:

标签: javascript reactjs use-state


【解决方案1】:

如何复制状态并使用括号表示法和点表示法推送以到达您需要更改的元素?

const boardlistCopy = JSON.parse(JSON.stringify(boardlist));
boardlistCopy[0].data[1].list.push({id: 2, task: "studying React"});
setBoardlist(boardlistCopy);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-07-07
    • 2016-04-29
    • 2020-09-10
    • 2020-03-28
    • 2019-01-10
    • 1970-01-01
    • 2020-11-02
    • 1970-01-01
    相关资源
    最近更新 更多