简体   繁体   中英

How to setState by using spread operations in react

i'm new to spread operations and i need some help or recommendations to add new replies to comment

my data structure is like this:

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

and new data:

{
    "id": 4,
    "comment_id": 2,
    "content": "fourth reply"
}

the thing i wanted to do is:

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
        })
    }))
}
const _reply = data =>
{
    let comment = this.state.comments.find(comment => comment.id === data.comment_id)
    if (comment) {
        comment = {...comment, replies: [...comment.replies, data]};
    }
    this.setState({
        comments: [...comments]
    })
}

When you want to merge the data on the basis of comment_id , you can do this,

const _reply = data =>
{
  this.setState(prevState =>({
    ...prevState,
    comments : prevState.comments.map(comment => (comment.replies[0].comment_id === data.comment_id) ? {...comment, replies: comment.replies.concat(data)} : comment
        )
  }), ()=>console.log(this.state.comments))
}

Simplified Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM