React各生命周期函数的调用顺序

刚开始学习react时总是搞不清楚相关函数的调用顺序,导致写出的代码可能存在不可预期的现象。后来写了一段验证代码,确定了调用顺序如下

- start
componentWillMount
render
componentDidMount
componentWillUpdate
render
componentDidUpdate
- setState
componentWillUpdate
render
componentDidUpdate
- changePropsInParentComponent
componentWillReceiveProps
componentWillUpdate
render
componentDidUpdate

验证代码如下

子组件MyChild代码

import React from 'react';

const lifeCircle = ['start'];

let hOutputTimer = null;
function addLog(msg) {
    lifeCircle.push(msg);

    if (hOutputTimer) {
        clearTimeout(hOutputTimer);
    }
    hOutputTimer = setTimeout(() => {
        console.log(lifeCircle.join('\r\n'));
        lifeCircle.length = 0;
        hOutputTimer = null;
    }, 10000)
}
export {addLog}

// implement of the CLASS
export default class MyChild extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            sss: '111'
        }
    }
    componentDidMount () {
        addLog('componentDidMount')
    }
    componentWillMount () {
        addLog('componentWillMount')
    }
    componentWillReceiveProps () {
        addLog('componentWillReceiveProps')
        this.setState({sss: 'cccc'})  // 这个setState不影响各函数的调用顺序
    }

    componentWillUpdate () {
        addLog('componentWillUpdate')
    }
    componentDidUpdate () {
        addLog('componentDidUpdate')
    }

    render() {
        addLog('render')
        return (
        <div>
            <button onClick={() => {
                addLog('setStateInSelfComponent'); 
                this.setState({sss:'222'})
            }}>sss</button>
        <div>{this.props.ppp}</div>
        <div>{this.state.sss}</div>
        </div>
        )
    }
}

父组件ParentComp代码

import React from 'react';
import MyChild from './mychild';

class ParentComp extends React.Component {

    state = {
        ppp: 'p111'
    }

    render () {
        return (
            <div>
                <button onClick={() => {
                    addLog('- changePropsInParentComponent');
                    this.setState({ppp:'p222'});
                }}>ppp</button>
                <MyChild ppp={this.state.ppp} />
            </div>
        );
    }
}

export default ParentComp

 

 


版权声明:本文为hdx_008原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。