首页 > 解决方案 > 如何在反应中将对象添加到嵌套状态?

问题描述

我正在创建简单的评论框,用户可以在其中回复评论。我已将状态定义如下:

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

        ],
        
    }

一个评论对象是一个评论,回复是用户对该评论的回复

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

我想要做的是当用户回复评论时让我们说评论有 id “TKT4321”然后将回复对象添加到该列表中。例如

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

如果回复已经存在于回复数组中,那么只需将{ id: "TKT341113", message: "ftrdgf" }对象附加到回复数组。例如

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

我的解决方案是:

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

但是有了这个我无法设置状态。我是新手,我很困惑如何设置嵌套对象的状态。请帮忙。

标签: javascriptreactjssetstatereact-state

解决方案


您将评论作为新状态返回,没有comments密钥,覆盖所有状态。相反,请执行以下操作:

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

推荐阅读