Detailed explanation of the use of state in React's three major attributes

Detailed explanation of the use of state in React's three major attributes

Data is needed in many places in React, which is called state in React. We need a special method to manage state, so state-related methods were born. State should be required to have two basic functions: first, it can store certain values ​​so that it can be used by react, and second, it can be monitored by react and re-rendered when it changes. Here we introduce how to write state in class and function components respectively:

Class Component

class ClassComponent extends React.Component{
    constructor(props){
        super(props)
    } //Optional render(){
        return (
            //You can write jsx syntax here)
    }
}

We generally use setState to change the state. We can directly pass an object to be changed or a callback function. Note that if an object is passed in, React only makes a shallow copy, not a deep copy. Therefore, if other objects in the object are changed, React cannot know to render. This method essentially passes in a new value and overwrites the original value. If this value is the same as the original value, React will not render.

Why is React so troublesome? Can't we just modify the value directly? Because in React, there is a concept called mutability. React knows what happened through the state changes in setState, so it renders. If the state is changed directly, React cannot perceive it and therefore cannot render. Simply put, it does not have two-way data binding like Vue.

The constructor in the class component can be written or not. There are two main functions of writing this constructor:

  • To assign an object to this.state to initialize the value of the internal state
constructor(props){
    super(props)
    this.state = {n:12}
}

render(){
    return (
        <div>
                <h1>THE TIME IS {this.state.n}</h1>
        </div>
    )
}

Note that setState cannot be written here. The above method React can also be set externally, that is,

state = {n:12}

render(){
    return (
        <div>
            <h1>THE TIME IS {this.state.n}</h1>
        </div>
    )
}
  • Bind an instance to an event handler
constructor(props){
    super(props)
    this.addNum = function(){fn()}.bind(this)
}

render(){
    return (
        <button onClick={this.addNum}>+1</button>
    )
}

However, this method has been replaced by a new method in React. The code is as follows:

addNum = ()=>{
    fn()
}

render(){
    return (
        <button onClick={this.addNum}>+1</button>
    )
}

Therefore, there is no need to write the above constructor to inherit the parent class method.

Functional Components

import { useState } from "react"
function FunctionComponent(){
    const [data,setData] = useState("the initial value you want to pass in")
    return (
        <div>SHOW DATA {state}</div>
    )
}

The function of setData here is similar to setState, but it can only be used to change the state of data, and a callback function is passed in when it needs to be changed. The function takes as its argument the previous value and returns the value to be changed. The essence of this method is to pass in a new object to change the value of the previous React object. For this purpose, you can also simply write the changed value directly. By default, it will correspond to the current object and change its value. The above method is much simpler than the original setState, but the trouble is that if there are multiple data, you need to useState multiple times and cannot pass in multiple values ​​at one time. However, in most cases, data management issues are managed by Redux, so React itself does not need to worry about it.

The pitfalls of setState

When changing the state of a React component, a common problem is the value merging of setState. Look at the following questions:

this.addNum = function () {
            this.setState({num:this.state.num+1})
            this.setState({num:this.state.num+1})
            this.setState({num:this.state.num+1})
        }.bind(this)

At this time, when the addNum function is triggered, num is only increased by 1. It didn't add 3 as we thought. React itself explains this:

Calling setState is asynchronous - don't expect this.state to be immediately mapped to the new value after calling setState.

The explanation for this is:

  1. No matter how many times you call setState, the updates are not performed immediately. Instead, store the state to be updated in '_pendingStateQuene' and the component to be updated in 'dirtyComponent';
  2. When the root component doesMount, the batch mechanism is updated to false. At this time, take out the state and components in '_pendingStateQuene' and 'dirtyComponent' and merge and update them;

Simply put, when React is executed, in order to improve performance, the setState to be updated will be stored in an array. When the synchronous code of React itself is executed, before the update, the setState in the array will be taken out and then rendered. In the above code, because we added the synchronous code this.setState({num:this.state.num+1}) to setState, when batch processing is taken out, a merge will occur, merging many setStates into one sentence, thus only changing 1. Because of this mechanism, setState looks like asynchronous code, but it is actually executed synchronously. At this time, if we change the previous synchronous code to asynchronous, we will get the result we want.

this.addNum = function () {
            setTimeout(()=>{ this.setState({num:this.state.num+1}) },0)
            setTimeout(()=>{ this.setState({num:this.state.num+1}) },0)
            setTimeout(()=>{ this.setState({num:this.state.num+1}) },0)
        }.bind(this)

At this point, the value is directly increased by 3, because the asynchronous code will be temporarily stored while the code is executed. It is executed after all synchronous codes are executed. At this time, the batch processing mechanism has ended, so all three functions are executed, so 3 is added. This is what I can think of so far. If there are new ones in the future, they will be added.

The above is the detailed content of the detailed explanation of the use of state, one of the three major attributes of React. For more information about the state, one of the three major attributes of React, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • In-depth understanding of the three core properties of React
  • How to deeply understand React's ref attribute
  • Detailed explanation of the use of Refs in React's three major attributes
  • Detailed explanation of the use of props in React's three major attributes
  • Do you know the three major properties of React?

<<:  Solution to 1449 and 1045 exceptions when connecting to MySQL

>>:  How to use Volume to transfer files between host and Docker container

Recommend

Detailed explanation based on event bubbling, event capture and event delegation

Event bubbling, event capturing, and event delega...

How to handle spaces in CSS

1. Space rules Whitespace within HTML code is usu...

Complete steps to build a squid proxy server in linux

Preface This article mainly introduces the releva...

Velocity.js implements page scrolling switching effect

Today I will introduce a small Javascript animati...

...

Detailed graphic explanation of how to clear the keep-alive cache

Table of contents Opening scene Direct rendering ...

Weather icon animation effect implemented by CSS3

Achieve results Implementation Code html <div ...

Vue implements the method example of tab routing switching component

Preface This article introduces the use of vue-ro...

Summary of four situations of joint query between two tables in Mysql

Generally speaking, in order to get more complete...

mysql method to view the currently used configuration file my.cnf (recommended)

my.cnf is the configuration file loaded when MySQ...

How to install and configure WSL on Windows

What is WSL Quoting a passage from Baidu Encyclop...

MySql COALESCE function usage code example

COALESCE is a function that refers to each parame...

Ideas and methods for incremental backup of MySQL database

To perform incremental backup of the MySQL databa...

Detailed explanation of Mysql communication protocol

1.Mysql connection method To understand the MySQL...