react=> setState advanced from zero

Keywords: React

setState has three features:

Code first:

export default class App extends Component {

  state = {
     n: 1
  }

  hClick = () => {
    this.setState({n: 100})
    console.log(this.state.n)// How much is printed here?
    console.log(document.getElementById('span').innerHTML) // How much is printed here?
  }

  render () {
    return (
      <div>
        <button onClick={this.hClick}>click</button>
        <span id="span">
          n: {this.state.n}
        </span>
      </div>
    )
  }
}

 

  You can see from this that setState can appear asynchronous, and after a setState call, it does not modify the value of the state immediately or update the dom immediately.

Question 2:

 

  As you can see here, when we call setState several times it merges, setState({object}) merges, and render() triggers once more.

Question 3:

 

So if we don't use it properly, it loops. In componentDidUpdate, calling setState() in render causes an endless loop

From the above, we can only summarize three features of setState:

  •   It can be asynchronous. After a setState call, the value of the state is not modified immediately, nor is dom updated immediately
  • Multiple calls merge. setState({object}) is merged and render() triggered once more uniformly
  • If used improperly, the cycle will end. In componentDidUpdate, calling setState() in render causes an endless loop

The second parameter of setState is:

Format 1:

this.setState({} [,callback])


// Callback functions are optional (this round of setState updates (page ui updates)) callback functions are called

Format 2:

this.setState((Previous state) => {
  return New State
}[,callback])

Take a look at a small case to learn more:

  state = {
    n: 1
  }

  hClick = () => {
    this.setState( preState => ({ n: preState.n + 1 }))
    this.setState( preState => ({ n: preState.n + 2 }))
    this.setState( preState => ({ n: preState.n + 3 }))
  }
  // What is n on the page?

The state can get the state of the overlay, suitable for multiple calls to setState  

Case 2:

  state = {
    n: 1
  }

  hClick = () => {
    this.setState( preState => ({ n: preState.n + 1 }), ()=>{console.log(this.state.n)})
    this.setState( preState => ({ n: preState.n + 2 }), ()=>{console.log(this.state.n)})
    this.setState( preState => ({ n: preState.n + 3 }), ()=>{console.log(this.state.n)})
  }
  // 1. What is n on the page?
  // 2.What will the three console.log s output?

  The state can get the latest status, which is suitable for getting the status after the state update.

setState Advanced-Synchronizer Asynchronous:

As mentioned in the three features of setState, setState can be asynchronous, is it synchronous or asynchronous?

It is said here that essentially setState is not an asynchronous method in itself, and it takes on an asynchronous form because of the performance optimization mechanism of the react framework itself.

In React, if event handling is initiated by React (such as via onClick), the call to setState does not synchronously update this.state, except that setState calls execute this.state synchronously. "In addition to this" refers to event handlers added directly through addEventListener bypassing React and asynchronous calls made through setTimeout || setInterval.

Simply put:

  • setState in React Processing (Event Callback, Hook Function) is an asynchronous update
  • SetState in unreacted setState (via addEventListener || setTimeout/setInterval) is a synchronous update.

Here's a picture:

On the whole; setState is a synchronous method, but react behaves asynchronously in react events for performance optimization.

Display code:

import reactDom from 'react-dom'

import React, { Component } from 'react'

class App extends Component {
  state = {
    n: 1
  }

  // setTimeout(() => {
  //   this.setState({ n: 2 })
  //   console.log(this.state.n)
  //   console.log(document.getElementById('btn').innerHTML)
  // }, 2000)

  componentDidMount () {
    // this.setState({ n: 2 })
    // console.log(this.state.n)
    // console.log(document.getElementById('btn').innerHTML)

    document.getElementById('btn').addEventListener('click', () => {
      this.setState({ n: 2 })
      console.log(this.state.n)
      console.log(document.getElementById('btn').innerHTML)
    })
  }

  click = () => {
    this.setState({ n: 2 })
    console.log(this.state.n)
    console.log(document.getElementById('btn').innerHTML)
  }

  render () {
    return (
      <div>
        {/* <button id="btn" onClick={this.click}> */}
        <button id="btn" onClick={this.click}>
          {this.state.n}
        </button>
      </div>
    )
  }
}

reactDom.render(<App />, document.getElementById('root'))

  More about setState can be seen: Is the setState of react synchronous or asynchronous? - Know ,https://segmentfault.com/a/1190000015463599 Detailed explanation

Posted by kenhess on Thu, 11 Nov 2021 09:12:19 -0800