【问题标题】:How to add object into nested state in react?如何在反应中将对象添加到嵌套状态?
【发布时间】:2020-08-03 07:53:18
【问题描述】:

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

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

        ],
        
    }

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

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

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

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

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

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

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

【问题讨论】:

    标签: javascript reactjs setstate react-state


    【解决方案1】:

    您将 cmets 作为新状态返回,没有 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" }]
                }))
            };
        })
    

    【讨论】:

      猜你喜欢
      • 2021-10-06
      • 1970-01-01
      • 2023-01-12
      • 2019-06-16
      • 2019-06-13
      • 2019-07-11
      • 1970-01-01
      • 1970-01-01
      • 2019-12-26
      相关资源
      最近更新 更多