The use of setState in React and the use of synchronous and asynchronous

The use of setState in React and the use of synchronous and asynchronous

In react, if you modify the state directly using this.state, it will not cause the component to be re-rendered. You need to use this.setState to modify the component's properties.

1. Two ways to define this.setState

Defining the initial state

state = { count: 0 },

If there is a button at this time, click the button to increase the count by 1, we can write it in two ways

(1) Transfer object

this.setState({ count: this.state.count + 1})

(2) Transfer function

this.setState((state, props) => ({ count: count + 1}))

2. What are the differences between the two methods of setState?

If the value of the changed state needs to depend on the value of the previous state, a function is needed, such as the following:

addCount(){
  this.setState({ count: this.state.count + 1})
  this.setState({ count: this.state.count + 1})
  this.setState({ count: this.state.count + 1})
}

At this time, only one +1 operation will be executed, because multiple setState operations will be merged inside React, and the new state will be merged by Object.assgin({}, {count: 0}, {count: 1}). The above assignment will be executed three times, but because the value of count is not updated, the final execution result is only +1. If the setState assignment is a function, the situation will be different.

addCount(){
  this.setState((state, props) => ({ count: count + 1}))
  this.setState((state, props) => ({ count: count + 1}))
  this.setState((state, props) => ({ count: count + 1}))
}

This operation will get a +3 effect, because React will make a judgment. If a function is passed in, it will execute this function, and the value of count will be modified at this time.

3. Is setState synchronous or asynchronous?

☆☆☆☆☆ is asynchronous

(1) That is, after we modify the state through this.setState, outputting the value of state in the next line will not get the new value

(2) Why asynchronous?

There are two reasons. One is to improve efficiency. Every time the state value is modified, the renderer will be re-rendered. Merging and updating the state value multiple times can improve performance. The other is that the renderer will be updated later. If there are subcomponents in the renderer, the props of the subcomponents depend on the state of the parent component, and the props and state cannot be consistent.

(3) How to obtain the state value during asynchronous operation?
① In the callback function of setState

this.setState({ 
  count: this.state.count + 1}}, 
  ()=>{ console.log(this.state.count)})

② Get it in componentDidUpdate

componentDidUpdate(){
  console.log(this.state.count)
}

☆☆☆☆☆ is synchronized

(1) That is, after we modify the state through this.setState, the next line outputs the new value of state

(2) In what scenarios is synchronization possible?
① Native js obtains dom elements and binds events

<button id="addBtn">Click me +1</button>
componentDidMount(){
   const addBtn = document.getElementById('addBtn')
   changeBtn.addEventListener('click',()=>{
       this.setState({ count: this.state.count + 1})
       console.log(this.state.message)
   })
}

② Timer setTimeout

<button onClick={ e => this.addOne() }>Click me +1</button>
addOne(){
setTimeout(()=>{ this.setState({ count: this.state.count + 1 })
 console.log(this.state.count ) },0)
}

This is the end of this article about the use of setState in React and the use of synchronous and asynchronous. For more relevant React setState synchronous and asynchronous content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Understanding of the synchronous or asynchronous problem of setState in React
  • Code analysis of synchronous and asynchronous setState issues in React
  • Use of setState synchronous and asynchronous scenarios in React

<<:  Detailed explanation of the mechanism and implementation of accept lock in Nginx

>>:  Some ways to eliminate duplicate rows in MySQL

Recommend

Brief introduction and usage of Table and div

Web front end 1 Student ID Name gender age 01 Zha...

Analysis of several situations where MySQL index fails

1. Best left prefix principle - If multiple colum...

How to redirect URL using nginx rewrite

I often need to change nginx configuration at wor...

Implementation of automatic completion of Docker commands

Preface I don't know how long this friend has...

Linux traceroute command usage detailed explanation

Traceroute allows us to know the path that inform...

Sample code using the element calendar component in Vue

First look at the effect diagram: The complete co...

Graphical tutorial on installing JDK1.8 under CentOS7.4

Linux installation JDK1.8 steps 1. Check whether ...

How to add sudo permissions to a user in Linux environment

sudo configuration file The default configuration...

Detailed explanation of Linux file operation knowledge points

Related system calls for file operations create i...

Detailed explanation of the basic functions and usage of MySQL foreign keys

This article uses examples to illustrate the basi...

Solution to the automatic termination of docker run container

Today I encountered a problem when I used Dockerf...

How to reduce the memory and CPU usage of web pages

<br />Some web pages may not look large but ...

Summary of 10 amazing tricks of Element-UI

Table of contents el-scrollbar scroll bar el-uplo...