javascript - 如何通过在反应中使用传播操作来设置状态
问题描述
我是传播操作的新手,我需要一些帮助或建议来添加新的评论回复
我的数据结构是这样的:
[
{
"id": 1,
"content": "first comment",
"replies": [
{
"id": 1,
"comment_id": 1,
"content": "first reply"
},
{
"id": 2,
"comment_id": 1,
"content": "seconds reply"
}
]
},
{
"id": 2,
"content": "second comment",
"replies": [
{
"id": 3,
"comment_id": 2,
"content": "third reply"
}
]
}
]
和新数据:
{
"id": 4,
"comment_id": 2,
"content": "fourth reply"
}
我想做的是:
const _reply = data =>
{
this.setState({
comments: // add new reply to comment by comment_id
})
}
解决方案
const _reply = data =>
{
this.setState(prevState =>({
...prevState,
comments : prevState.comments.map(comment => {
if(comment.id === data.id) return {...comment, replies: comment.replies.concat(data)}
return comment
})
}))
}
推荐阅读
- google-maps - 从 Google Maps Routing 获取数值(距离/持续时间)
- terraform - 使用 terraform 的 Datadog 监视器
- android - 访问 AlertDialog 的布局
- c# - 如何使用 C# WPF 和 EF6 将对象正确添加到 localDB 和 listview?
- java - Java:尝试使用 BufferedReader 读取在同一项目的不同包中导入的文本文件?没有得到这样的文件或目录错误?
- python - Tensorflow:自定义指标:ValueError:不支持无值
- sql - 使用 Pyodbc,ODBC 驱动程序不起作用,但使用常规 SQL Server 驱动程序,为什么?
- python - 不知道整个 unicode 字符 python
- python - 如何使 API 端点呈现交互式图表
- flutter - SQFLite 插件从数据库返回布尔文本的空值,尽管之前已设置