react中component生命周期

前言

参考了很多文章,结合实例写下我自己的理解

react中component生命周期主要分为三个阶段:加载、更新和卸载

1、加载(Mounting) 主要包含4个方法

constructor()componentWillMount()render()componentDidMount()

2、更新(Updating) 主要包含5个方法

componentWillReceiveProps()shouldComponentUpdate()componentWillUpdate()render()componentDidUpdate()

3、卸载(Unmounting) 主要包含1个方法

componentWillUnmount()

实例代码

import React from 'react';

class LifeCycleTracking extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            content: 'This is lifecycle tracking content'
        }

        console.log("Contructor...");
    }
    componentWillMount() {
        console.log("Will Mount...");
    }
    componentDidMount() {
        console.log("Did Mount...");
    }
    componentWillReceiveProps() {
        console.log("Will Receive Props...");
    }
    shouldComponentUpdate() {
        console.log("Update true");
        return true;
    }
    componentWillUpdate() {
        console.log("Will Update...");
    }
    componentDidUpdate() {
        console.log("Did Update...");
    }
    componentWillUnmount() {
        console.log("Will Unmount...");
    }
    render() {
        console.log("Render...");
        return (
            <div>
                <h2>{this.props.title}</h2>
                <p>{this.state.content}</p>
            </div>
            );
    }
}

export default LifeCycleTracking;

进入页面时

扫描二维码关注公众号,回复: 2368934 查看本文章

当change state时

可以看到,当进入页面时,会先执行constructor()函数

constructor(props):该方法在组件加载前调用。当组件作为React.Component的子类实现时需要在其他声明之前先调用super(props)。否则,this.props在构造器中会是undefined,这会导致代码出现bug。 

作用:用来初始化状态,如果既不初始化状态也不绑定方法,那就没必要实现该方法了。(注:事实上,如果组件没有构造器方法的话,组件会默认调用一个构造器,实现属性的传递)。

只要组件存在constructor,就必要要写super,否则this指向会错误

执行完constructor()函数之后,会依次执行componentWillMount()render()componentDidMount()函数

componentWillMount():组件刚经历constructor(),初始完数据,组件还未进入render组件还未渲染完成,dom还未渲染,一般不用。

render():该方法必须要有,主要提供渲染页面的数据,调用该方法时,会检查其中的props和state,以此来渲染页面。

componentDidMount():说明第一次渲染已完成,此时dom节点已经生成,可以在这里调用ajax请求,返回数据setState后组件会重新渲染,也可以在此处设置定时器等。 

            注:在此处设置状态等会导致页面重新渲染

到此为止,页面的第一次渲染结束,此时,如果更新了state,页面会进行第二次渲染,会依次执行componentWillReceiveProps()shouldComponentUpdate()componentWillUpdate()render()componentDidUpdate()函数。

componentWillReceiveProps()该方法会在加载好的组件在收到新的状态后调用。它接受一个参数nextProps,通过对比nextProps和this.props,将nextProps setState为当前组件的state,从而重新渲染组件。

shouldComponentUpdate():简单理解为这个component需不需要更新,在react中,父组件更新之后,所有的子组件都会相应更新,但这时我们不需要子组件更新,可以在此方法中return false,即可阻止更新。

componentWillUpdate():shouldComponentUpdate返回true以后,组件进入重新渲染的流程,进入componentWillUpdate,这里同样可以拿到nextProps和nextState。

componentDidUpdate():可用来在组件更新后操作DOM,这里可以拿到更新前的props和state,通过比较当前属性和之前属性来决定是否发送网络请求(如,状态未改变不需要做网络请求)。 

当点击unMount时,会执行componentWillUnmount()方法。

componentWillUnmount():该方法会在组件被销毁前立即调用。 
作用:可以在方法内实现一些清理工作,如清除定时器,取消网络请求或者是清理其他在componentDidMount()方法内创建的DOM元素。

这就是react component生命周期的简单学习经验啦,任重而道远,努力终会成功。

 

猜你喜欢

转载自www.cnblogs.com/kennethDu/p/9367167.html