React生命周期如下图所示:
通过这张图你可以看到React声明周期的***四个大阶段***:
***Initialization:初始化阶段。
Mounting: 挂载阶段。
Updation: 更新阶段。
Unmounting: 销毁阶段***
什么是生命周期函数
生命周期函数指在某一个时刻组件会自动调用执行的函数
constructor不是生命周期函数,我们称它为构造函数。
Mounting阶段
Mounting阶段叫挂载阶段,伴随着整个虚拟DOM的生成,它里边有三个小的生命周期函数,分别是:
componentWillMount : 在组件即将被挂载到页面的时刻执行。
render : 页面state或props发生变化时执行。
componentDidMount : 组件挂载完成时被执行。
注意的问题
componentWillMount和componentDidMount这两个生命周期函数,只在页面刷新时执行一次,而render函数是只要有state和props变化就会执行。
Updation阶段
shouldComponentUpdate函数
shouldComponentUpdate函数会在组件更新之前,自动被执行,它要求返回一个布尔类型的结果,必须有返回值
componentWillUpdate函数
componentWillUpdate在组件更新之前,但在shouldComponenUpdate之后被执行。但是如果shouldComponentUpdate返回false,这个函数就不会被执行了。
componentDidUpdate函數
componentDidUpdate在组件更新之后执行,它是组件更新的最后一个环节。
componentWillReceiveProps 函数
子组件接收到父组件传递过来的参数,父组件render函数重新被执行,这个生命周期就会被执行。
也就是说这个组件第一次存在于Dom中,函数是不会被执行的;
如果已经存在于Dom中,函数才会被执行。
UnMounting阶段
componentWillUnmount函數
这个函数是组件从页面中删除的时候执行