01-React-生命周期-执行时机

发布时间 2023-09-23 12:26:18作者: 爱杨帅

生命周期概述

事物从生到死的过程, 我们称之为生命周期

什么是生命周期方法

事物在从生到死过程中, 在特定时间节点调用的方法, 我们称之为生命周期方法

例如像我们人类,从生到死的过程有这么几个特定的时间点,就是上,幼儿园,小学,中学...

React 组件生命周期方法

组件从生到死的过程, 在特定的时间节点调用的方法, 我们称之为组件的生命周期方法

官方文档:https://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/

image-20220429094852545

  • constructor 函数: 组件被创建的时候, 就会调用
  • render 函数: 渲染组件的时候, 就会调用
  • componentDidMount 函数:组件已经挂载到 DOM 上时,就会回调
  • componentDidUpdate 函数:组件已经发生了更新时,就会回调
  • componentWillUnmount 函数:组件即将被移除时,就会回调

经过了如上的介绍方法之后,我们再来一一的写个 demo 试一下就好了,该知识点就可以过掉了。

挂载时阶段

App.js:

import React from 'react';

class Home extends React.Component {
    constructor(props) {
        super(props);
        console.log('挂载时-constructor');
    }

    render() {
        console.log('挂载时-render');
        return (
            <div>
            </div>
        )
    }
    componentDidMount() {
        console.log('挂载时-componentDidMount');
    }
}

class App extends React.Component {
    render() {
        return (
            <div>
                <Home/>
            </div>
        )
    }
}

export default App;

image-20220429112644738

更新时阶段

App.js:

import React from 'react';

class Home extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            count: 0
        }
    }

    render() {
        if (this.state.count === 0) {
            console.log('挂载时-render');
        } else {
            console.log('更新时-render');
        }
        return (
            <div>
                <button onClick={() => {
                    this.btnClick()
                }}>Home按钮
                </button>
            </div>
        )
    }

    componentDidUpdate(prevProps, prevState, snapshot) {
        console.log('更新时-componentDidUpdate');
    }

    btnClick() {
        this.setState({
            count: 1
        });
    }
}

class App extends React.Component {
    render() {
        return (
            <div>
                <Home/>
            </div>
        )
    }
}

export default App;

image-20220429134554011

卸载时阶段

App.js:

import React from 'react';

class Home extends React.Component {
    render() {
        return (
            <div>
                <p>Home</p>
            </div>
        )
    }
    componentWillUnmount() {
        console.log('卸载时-componentWillUnmount');
    }
}

class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            flag: true
        }
    }

    render() {
        return (
            <div>
                {this.state.flag && <Home/>}
                <button onClick={() => {
                    this.btnClick()
                }}>App按钮
                </button>
            </div>
        )
    }

    btnClick() {
        this.setState({
            flag: false
        });
    }
}

export default App;

image-20220429113218497