Study notes-react's life cycle hook function


The life cycle of react is roughly divided into three stages: component creation, component update, and component destruction. And only class components have life cycle hook functions, function components do not.

Figure 1. React life cycle hook function

1. Component creation: 

Figure 1 shows the execution sequence of the hook function of the life cycle.

1.constructor():

The data can be initialized by this.state assignment object.

Bind an instance for the event handler.

constructor(props) {
    super(props);
    this.state = {
        a: 10,
        b: 100
   };
   this.changeName = this.changeName.bind(this);
}

It is executed only once when the component is created, and will not be executed thereafter.

2.static getDerivedStateFromProps():

This function is used to assign initial values ​​to the component as a subcomponent, and the component can modify the data in its own state.

A judgment is usually made inside the function. If the component modifies the data in its own state, the data in the props from the parent component is not needed.

It will be called during the component creation and update phases.

There is no this pointer, and there are two parameters. The first parameter is the data in the props from the parent component, and the second parameter is the data in the state of the component.

Must return an object or null. If it is an object, it will be merged into the state of this component.

static getDerivedStateFromProps(nextProps, prevState) {
    if(nextProps.b !== prevState.prevProps.b) {
        return {
            b: nextProps.b,
            prevProps: { b: nextProps.b }
        };
    }else
        return null;
}

3.componentWillMount() || UNSAFE_componentWillMount():

Calling setState in this function will not trigger additional rendering. But this function can be implemented directly in the constructor. Therefore, this function has no meaning and is basically in an obsolete state.

4.render(): 

The main part of the rendering page, which can implement some operations, but must return a jsx object.

The core code will be called repeatedly, reducing the number of unnecessary render() function calls can achieve performance optimization.

render() {
    // 核心代码,会被反复调用
    console.log("render函数运行了");
    return (
        <div>这是个人中心
            <Child b ={this.state.b}></Child>
        </div>
    );
}

 5.componentDIdMount():

Will be called after the component is mounted. Component mounting is to insert into the dom tree.

In this function, the dynamic data required by the ajax request component is usually sent.

Calling setState here will trigger the render() function.

componentDidMount() {
    // 组件挂载完毕
    let listMain = await http("/category/list/0");
    this.setState({  listMain });
    this.changeCategory(listMain[0].id);
}

 2. Component update:

How to trigger component update:

1. This component calls setState by itself, it will trigger re-render (re-rendering).

2. The parent component triggers re-render, and the child component is re-rendered.

3. The props change will trigger the re-render of this component.

1.componentWillReceiveProps() || UNSAFE_componentWillReceiveProps():

This component is called when the component is updated, and is usually used: when the value of props changes, perform corresponding operations in this function in response to the change of props value.

This component has been basically obsolete. You can do the corresponding operation in componentDidUpdate.

2.static getDerivedStateFromProps():

The operation is the same as when the component was created. See Component Creation for details.

3.shouldComponentUpdate():

This function is mainly used to optimize the performance of reacr.

The function must explicitly return a true or false.

Two parameters, the first parameter is nextProps: props value that is about to take effect, and the second parameter is nextState: state value that is about to take effect. Get the current value of this pointer.

Write reasonable logic to reduce unnecessary updates. If return false; it will not execute downwards, which reduces the number of renders and optimizes performance.

shouldComponentUpdate(nextProps){
    console.log("child组件的shouldComponentUpdate运行了");
    return this.props.b !== nextProps.b;
}

// 如果不写默认返回true

The code for render optimization is as follows:

shouldComponentUpdate(nextProps){
    let keys = Object.keys(nextProps);
    for(let i = 0; i < keys.length; i++) {
        if(this.props[keys[i]] !== nextProps[keys[i]] ) return true;
    }
    return false;
}

 It is equivalent to the default shouldComponentUpdate() function of the class component inherited from pureComponent of react. 

import React, {PureComponent} from 'react';

class Child extends PureComponent {}

PureComponent compares all the properties in props and first determines whether the current component needs re-render.

But: PureComponent only does a simple "shallow comparison" of property values.

Shallow comparison is okay for value types. For reference types, it only compares whether their addresses in memory are the same, and does not perform deep-level comparisons.

If a reference type with a different address and the same content is passed, PureComponent cannot perform in-depth comparisons.

Use case: When you know that a component is a class component, and this class component needs to be optimized for performance.

The biggest pitfall: when a parent component passes data of a reference type to a child component, it cannot be bound directly when passing a value. E.g: 

// 错误写法
<Child b ={this.state.b} changeName={this.changeName.bind(this)}></Child>

// 正确写法
changeName = () => {};
<Child b ={this.state.b} changeName={this.changeName}></Child>

4.componentWillUpdate() ||  UNSAFE_componentWillUpdate():

This method has been deprecated, you can use componentDidUpdate() to replace the function of this function.

If you need to read dom information, you can use getSnapshotBeforeUpdate instead.

componentWillUpdate(){
    // 基本废弃,一般不用了。改名了UNSAFE_componentWillUpdate
    console.log("componentWillUpdate函数运行了");
}

5.render():

In the update stage rendering, the dom node of the component can be rendered according to the new data. The dom node will be compared with the last time and find out the different nodes to modify. Not all dom nodes are re-rendered.

6.getSnapshotBeforeUpdate():

Generally perform some dom operations in this function. Record the scroll position.

For example: a scrollable page, after a sudden refresh, you need to record its position in this function, and then pass it to the componentDidUpdate() function, you can return to that position after the update is over.

There are two parameters: prevProps, prevState whose content is the same as above.

Need to return a value return

getSnapshotBeforeUpdate(prevProps, prevState){
    return { y: 50 }
}
componentDidUpdate(prevProps, prevState, snapshot){
    console.log(snapshot) // { y: 50 }
}

7.componentDidUpdate():

This function is mainly executed when the update is complete.

There are two parameters: the first parameter is prevProps, the props value before the update, and the second parameter represents the value in the state before the update. The current value is this.props. The third parameter is the data passed by getSnapshotBeforeUpdate().

The implementation is similar to watch monitoring in vue. By comparing the data before and after the update.

This function indicates that the dom corresponding to the latest state has been updated, so you can do some custom operations on the latest dom.

// 模拟vue中的watch监听
componentDidUpdate(prevProps,prevState) {
    if(prevState.a !== this.state.a) {
        console.log("a变量");
    }
}

// 对最新的dom做些自定义操作
// 例如使用插件监听滚动

3. Component destruction:

Components that are no longer in use or have not been used for a long time need to be destroyed.

1.componentWillUnmount():

 This function is mainly used to release related memory space and resources.

// 组件销毁
componentWillUnmount() {
    // 释放当前组件相关的内存和资源
    console.log("componentWillUnmount运行了")
}

The above is the hook function of the life cycle in react, and different functions can be realized through different functions.

The execution sequence of the life cycle hook functions in the parent and child components is as follows:

The constructor and render functions of the parent component are executed before the child component, and the componentDidMount and componentDidUpdate of the child component are executed before the parent component.

Guess you like

Origin blog.csdn.net/qq_41339126/article/details/109504150