On the updating of arrays in React state

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.

May.22,2021

Three important functions in

setState are:

  1. merge state
  2. trigger the reconciliation algorithm and render
  3. batch updates

and it's not that only setState can change state.


The value of

righteously emptying comment is the code this.state.comment='' . The code
this.setState ({}) has no effect.

the reason starts with memory.
state exists in the component as object . You can understand that this.state points to the area where state is stored, not state itself.
when you execute this.state.xxx = yyyy , the original value of state in memory is changed, and the reference does not change, so what you see occurs.

Menu