javascript - 如何在反应中将对象添加到嵌套状态?
问题描述
我正在创建简单的评论框,用户可以在其中回复评论。我已将状态定义如下:
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" }]
}))
})
但是有了这个我无法设置状态。我是新手,我很困惑如何设置嵌套对象的状态。请帮忙。
解决方案
您将评论作为新状态返回,没有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" }]
}))
};
})
推荐阅读
- docker - Cloud Run 和 Revel 容器
- python - 使用 python json 转义字符
- sql - 根据其他查询的结果运行 Select 查询
- flutter - FutureBuilder、SetState:删除 setState 时变量未更新
- jquery - jQuery:保存和恢复多选框的选择状态
- r - 如何在绘图中添加相关值( ggplot )
- apollo - Apollo GraphQL 出现“不变违规”错误
- c# - 使用 C# 9 记录添加评论的正确方法是什么?
- swift - 快速接受任何类型测量的函数
- r - 使用 position_jitterdodge 对多面图中的点进行子集化