problem description
I always thought that the modification of state in React had to be modified with the setState function, but the push, of the array in the first direct state in the following code also modified state,. I don"t know why.
related codes
//
onClick() {
//
let newComment = {
content: this.state.comment,
date: dayjs().format("YYYY/MM/DD HH:mm:ss"),
id: Date.now()
}
//a
this.state.commentList.push(newComment)
//b
// this.setState({
// commentList: [newComment,...this.state.commentList]
// })
//c
this.setState({
comment:""
})
}
the effect of + a code is normal. It feels like transaction control. If you call the setState function, you will finish state modifying Synchronize, no matter what parameters are passed in the setState.
this.state.comment=""
this.setState({
})
this code also clears the comment normally.