简体   繁体   中英

How to add object into nested state in react?

I'm creating simple comment box where user can reply on comment. I have defined state as follows:

  this.state = {
       comments: [
            {
                id: "TKT4321",
                message: "abc",
               
            },
            {
                id: "TKT34341",
                message: "cccccc",
                reply: [
                    { id: "TKT34343", message: "aaaaa" },
                ]
            },

        ],
        
    }

one object of coments is one comment and reply is user replied on that comment

          {
                id: "TKT34341",
                message: "cccccc",
                reply: [
                    { id: "TKT34343", message: "aaaaa" },
                ]
            },

what i want to do is when user replied on comment let's say on comment having id "TKT4321" then add reply object to that list. eg

              {
                id: "TKT4321",
                message: "abc",
                 reply: [
                    { id: "TKT34343", message: "gfgfg" },
                ]
            },

If the replies are already there in the reply array then just append { id: "TKT341113", message: "ftrdgf" } object to reply array. eg

               {
                id: "TKT34341",
                message: "cccccc",
                reply: [
                    { id: "TKT34343", message: "aaaaa" },
                    { id: "TKT341113", message: "ftrdgf" },
                ]
            },

my soltuion is:

    this.setState((state) => {
        const { comments } = state.comments
        return comments.map((item) => ({
            ...item,
            reply: [...item.reply, { id: "TK2222", message: "jkjk" }]
        }))
    })

But with this i'm not able to set the state. I'm new to react and i'm confused how to set the state of nested objects. Please help.

You are returning the comments as a new state, without the comments key, overwriting all state. Instead, do this:

 this.setState((state) => {
        const { comments } = state.comments
        return {  // Add an object around the comments
            comments.map((item) => ({
                ...item,
                reply: [...item.reply, { id: "TK2222", message: "jkjk" }]
            }))
        };
    })

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