Take you to understand the life cycle of react (detailed explanation of the react life cycle, the whole process from creation to destruction)

foreword

The life cycle is actually the whole process from creation to destruction. We found that many frameworks involve the life cycle. Why do these frameworks need to design the life cycle, because we need to understand the execution process of our code. And what is the order of their execution, and at the same time, different constructors are exposed in different life cycle stages, and in different constructors we can do a lot of different functions. In React, a class component created by extends Component will have a life cycle

The four stages of the react life cycle

  1. Component initialization phase :
    getInitialState : initialize the value of this.state, call only once before the component is loaded
    getDefaultProps : only call once when the component is created and cache the returned object (that is, it will be called after React.createClass).
    Because this method is called before the instance is initialized, you cannot rely on this to get an instance of this component in this method.
  2. Component loading phase :
    componentWillMount : will only be called once before mount
    componentDidMount : will only be called once after mount is complete
  3. Component update phase :
    componentWillReceiveProps , shouldComponentUpdate, componentWillUpdate, componentDidUpdate These methods will not be called in the cycle of the first render component.
  4. Component destruction phase :
    componentWillUnmount : triggered by unmounting a component

Case description

For the above life cycle process, let's write a case to feel it:
The key point is to see the comments in the code:

import React, {
    
     Component } from 'react'

export class Button extends Component {
    
    
    constructor(props) {
    
    
        super(props)
        this.state = {
    
     liked: false }
        // 我们要执行的第一个阶段就是初始化阶段
        console.group('%c 1-初始化阶段', 'color: red', props, this.state)
    }
    // 逐渐被淘汰,需要使用就要加UNSAFE_不加会出现警告,此生命周期DOM未渲染
    // 只会在挂载之前调用一次,在render之前调用,一般我们可以在这个阶段发起请求
    // 还可以在这里调用setState改变状态,并且不会导致额外调用一次render
    UNSAFE_componentWillMount() {
    
    
        console.group('%c 2-组件加载前', 'color: green')
    }
    componentDidMount() {
    
    
        // 在这里请求也可以,此时DOM节点已经生成
        // 只在挂载完成之后调用一次,在render之后调用,从这里可以获取DOM节点
        console.group('%c 4-组件加载后', 'color: orange')
    }
    hanleClick(e) {
    
    
        this.setState({
    
     liked: !this.state.liked })
    }
    shouldComponentUpdate() {
    
    
        console.group('%c 5-数据是否需要更新', 'color: #00ae9d')
        // return true代表组件需要更新,false表示不用更新,实际业务开发中我们一般不用这个
        // return false
        return true
    }
    UNSAFE_componentWillUpdate(nextProps, nextState) {
    
    
        console.log(nextProps, nextState)
        console.group('%c 6-更新前', 'color: #885233')
    }
    componentDidUpdate(prevProps, prevState) {
    
    
        console.log(prevProps, prevState)
        console.group('%c 7-更新后', 'color: #777663')
    }
    componentWillUnmount() {
    
    
        // 这里主要完成组件的卸载和数据的销毁,清除组件所有的setTimeout,setInterval,移除所有的事件监听
        console.log('8-组件销毁')
    }

    render() {
    
    
        // 只要状态发生变化,一定会执行render方法
        // render函数会插入jsx生成的DOM结构,react会生成一个虚拟DOM树,在每一次组件更新的时候,react会通过其diff算法比较更新前后的新旧DOM
        // 比较以后,找到最小的差异DOM,进行重新渲染
        console.group('%c 3-组件加载前render', 'color: blue')
        const text = this.state.liked ? '喜欢' : '不喜欢'
        return (
            <button onClick={
    
    this.hanleClick.bind(this)}>{
    
    text}学习react!</button>
        )
    }
}

export default Button

Click the button: go through the life cycle as shown in the figure
insert image description here
Click the button again to update:
the life cycle of executing the update
insert image description here
If it is not clear, look at the picture directly, compare the code and results in the above example, it is clear at a glance:

insert image description here

Summarize

The react life cycle can also be roughly divided intoinitialization renew destroyThree stages, each stage has several life cycle functions and one-to-one numbers

initialization

At first, the build function is called to initialize the state of the component, then the getDerivedStateFromProps function will be called to detect whether the state and props have changed, and then the rendering logic render() function will begin to execute, at this time, the ui will be rendered. Finally, componentDidMount will be executed.

初始化
构建函数
getDerivedStateFromProps
render :渲染UI
componentDidMount

renew

As long as the props or stats in the component change, the component will enter the update phase:
the getDerivedStateFromProps function is executed first to detect whether the state and props have changed, and then shouldComponentUpdate is executed to determine whether the component needs to be updated. If it needs to be updated, then The render function will be executed, and the ui will be re-rendered according to the changes of state or props. After rendering, componentDidUpdate will be executed, and some logic after component update is processed here.

getDerivedStateFromProps
shouldComponentUpdate
render :渲染UI
更新
componentDidUpdate

destroy

Finally, when the mission of this component is over, it will die.
The componentWillUnmount function will be called, where we recycle memory, delete event listeners, etc., the component will be finally destroyed after the processing is complete

componentWillUnmount
销毁

This article is here. If it is helpful to you, please like, follow and support it~ I
will continue to bring you high-quality content in the future~

Guess you like

Origin blog.csdn.net/weixin_45745641/article/details/123476060