简体   繁体   中英

How to setState for nested array of object in react?

This is the object, lets say I'm gonna add something inside list: [], how can I do that? I know like we can do it using the prevList callback but I'm kind of confused to map through it.

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

What about make a copy of the state and just push using the bracket notation and dot notation to reach the element that you need to change?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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