首页 > 解决方案 > 如何通过在反应中使用传播操作来设置状态

问题描述

我是传播操作的新手,我需要一些帮助或建议来添加新的评论回复

我的数据结构是这样的:

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

标签: javascriptreactjs

解决方案


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
        })
    }))
}

推荐阅读