【发布时间】: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