Understand setState

In the recent study react source, originally from the entrance line by line to see the results of function calls follow the jump to jump to the giddy later decided to bring a purpose to see the source code, look at each study only one thing. A began to want to know is full of magic setState. This article is some of my understanding of the setState, inappropriate welcome message corrections.

setState basis devilish

Look at the situation below a few examples of output.

Synthesis Example 1 in the event setState

import React from 'react';

export default class SetState extends React.Component {
    constructor(props) {
        super(props);
    }

    state = {
        count: 0
    }

    click = () => {
        this.setState({
            count: this.state.count + 1,
        })
        console.log('count1', this.state.count);
        this.setState({
            count: this.state.count + 1,
        });
        console.log('count2', this.state.count);
    }

    render() {
        return (
            <div onClick={this.click}>
                count的值{this.state.count}
            </div>
        )
    }
}
// 打印:
// count1 0
// count2 0

2 embodiment functions in the life cycle setState

import React from 'react';

export default class SetState extends React.Component {
    constructor(props) {
        super(props);
    }

    state = {
        count: 0
    }
    
    componentDidMount () {
        this.setState({
            count: this.state.count + 1,
        })
        console.log('count1', this.state.count);
        this.setState({
            count: this.state.count + 1,
        });
        console.log('count2', this.state.count);
    }

    render() {
        return (
            <div>
                count的值{this.state.count}
            </div>
        )
    }
}
// 打印:
// count1 0
// count2 0

Example 3 setTimeout in setState

import React from 'react';

export default class SetState extends React.Component {
    constructor(props) {
        super(props);
    }

    state = {
        count: 0
    }

    componentDidMount () {
        setTimeout(() => {
            this.setState({
                count: this.state.count + 1,
            })
            console.log('count1', this.state.count);
            this.setState({
                count: this.state.count + 1,
            });
            console.log('count2', this.state.count);
        }, 0);
    }

    render() {
        return (
            <div>
                count的值{this.state.count}
            </div>
        )
    }
}
// 打印:
// count1 1
// count2 2

Example 4 Promise of setState

import React from 'react';

export default class SetState extends React.Component {
    constructor(props) {
        super(props);
    }

    state = {
        count: 0
    }

    componentDidMount () {
        Promise.resolve()
        .then(() => {
            this.setState({
                count: this.state.count + 1,
            })
            console.log('count1', this.state.count);
            this.setState({
                count: this.state.count + 1,
            });
            console.log('count2', this.state.count);
        })
    }

    render() {
        return (
            <div>
                count的值{this.state.count}
            </div>
        )
    }
}
// 打印:
// count1 1
// count2 2

The output from the Examples 1 and 2 of view, the value of direct access state after setState found no update, update state setState seems asynchronous process;

From 3, 4 outputs results of Examples Example view, the setState update operation is a synchronous state can immediately get the updated results.

In other words, setState sometimes is sometimes asynchronous is synchronous, really very evil. According to some online articles and their experiments can draw the following conclusions.

  • In the synthetic event, the life cycle of setState function is asynchronous batch updates, can not immediately get updated results, many times only to go once render setState
  • setState in setTimeOut, setInterval, native event, Promise are synchronized individually updated, you can get immediate updates of state, and each will go once render setState

About bulk update or non-batch update can render print view function

setState magic show Secret

SetState understanding of asynchronous batch update

Below is a schematic diagram of asynchronous batch updates

SetState understanding of asynchronous batch update

Here called Main Process call code written in synthetic event, setTimeout and the like.

E.g. below componentDidMountexecution of the code in the call Main process.

componentDidMount () {
    this.setState({
        count: this.state.count + 1,
    });
    console.log('count1', this.state.count);
    this.setState({
        count: this.state.count + 1,
    });
    console.log('count2', this.state.count);
}

Analysis on top of this seemingly cattle x Figure bonded directly to the code.

First, perform a setState, judgment is setState operations, create an update task to update the queue to join, to the focal point, the focal judge is not required to update, continue to execute code in the main Process.

Encountering the first console, direct execution, while printing out the state, apparently did not update the state or the original value, and then perform the Main Process code.

The second encounter setState, pay attention this time out of state is not updated, and then create an update task to update the queue, to the focal point, the focal judge is not required to update, continue to execute code in the main Process. Then executed console, out of state is not updated.

After a certain time, scheduling coordination center again, we found to update, and then perform the update queue of two tasks, get a new state, and then update this.stateand view.

From the above analysis we can understand why the value of the previous two console are printed.

There is a black box, how to run a focal point, which is later to be studied, and it is not clear, you can guess where it should have a side or something similar setTimeout setTimeout's.

Synchronous single update understanding of setState

Below is a schematic diagram of the synchronization update

Synchronous update understood by one of setState

Here is a piece of code to analyze the combined

import React from 'react';

export default class SetState extends React.Component {
    constructor(props) {
        super(props);
    }

    state = {
        count: 0
    }

    click = () => {
        setTimeout(() => {
            this.setState({
                count: this.state.count + 1,
            })
            console.log('count1', this.state.count);
            this.setState({
                count: this.state.count + 1,
            });
            console.log('count2', this.state.count);
        }, 0);
    }
    
    render() {
        return (
            <div onClick={this.click}>
                count的值{this.state.count}
            </div>
        )
    }
}

First encountering the first setState, judgment is setState, create an update task to update the queue, and then enter the focal point to coordinate center by some means to determine the need to synchronize the update directly perform the update task queue, to get the new state, and then update view, continue to execute code in the Main Process.

Encountered console, direct execution, remove the state (note the updated) promise.

Then they met setState (Note that to get the state is updated), to create update tasks into the update queue, and then enter the focal point to coordinate center by some means to determine the need to synchronize the update directly perform the update queue of tasks, get the new state, and then update the view, continue to execute code in the Main Process.

Again encountered console, direct execution, remove the state (of note is the secondary) promised.

From the above analysis we can see the synchronization setStateWhy are synchronized, the reason is that he does not judge an asynchronous process, directly update the state.

Several problems to be solved

  • The focal point is when and how to determine the need updating
  • How is the coordination center is to identify a setState in setTimeout or during the synthesis of the event or will the life cycle and the like.

Egg

Talk about the reading experience react source, looking directly at the beginning src directory, react part was okay, easier.

But to react-domdie, all kinds of calls, all kinds of mess of things, sometimes jumping followed by a function call, the results began to think why most are forgotten, so read really hurt people.

In fact, more than read the source code organization understand its methods, but to understand the core principles.

Below are a few tips:

  1. Reading the source code with a problem, especially in the beginning read, if read aimlessly, will be no sense of accomplishment, even a strong sense of frustration, learn to read for a long time do not know what
  2. react-dom The src code organization is very complex, it is recommended to compile the development version of the product directly read, in a file, it is easier to find.
  3. Multi-breakpoint, you can break point directly in the development version of the compiler product look, very convenient
  4. Do not tangle too much detail, to have superficial understanding attitude, do not know where you can temporarily let go

summary

setState confusing is an easy thing, especially for beginners react, may feel a little blurred. In this paper, the source synchronous and asynchronous own understanding of the mechanisms setState to do some analysis and some places may not be very accurate but hoping to help confused setState synchronous asynchronous mechanisms friend understand some of the principles involved. Finally remember what the scene is updated simultaneously, what the scene is asynchronous updates, this is to write code that can actually use to.

Guess you like

Origin www.cnblogs.com/floor/p/11567602.html