一.React生命周期函数概述
生命周期函数指在某一时刻组件会自动调用执行的函数,如下是React生命周期图解
(1)Initialization
对React组件来说,它会经历一些过程,Initialization指的是初始化过程,这个时候组件会初始化一些自己的数据,比如说props,state,在我们的组件里面在哪里做的初始化呢,constructor就是我们初始化的位置,在这个函数里面会接收props,定义state
(2)Mounting
接着呢,初始化以后一个组件要被渲染挂载到页面之上,所以会经历一个流程叫Mounting,Mounting就是挂载的意思,挂载会经历几个周期:
componentWillMount和componentDidMount只在页面第一次被挂载的时候执行, 数据变化只是更新render函数
// 在组件即将被挂载到页面的时刻自动执行
componentWillMount(){
console.log('componentWillMount');}
// 组件被挂载到页面之后,自动被执行
componentDidMount() {
console.log('componentDidMount');
}
(3)Updation
在组件更新的过程中也会涉及到新的生命周期函数,组件更新发生在什么情况下,要么是props发生变化,要么是state发生变化,数据发生变化时,页面的更新会被执行,props发生变化和state发生变化的时候,生命周期函数有所不同,差异就在componentWillReceiveProps
// 组件被更新之前,他会自动被执行
shouldComponentUpdate() {
console.log('shouldComponentUpdate');
return true;
}
// 组件被更新之前,它会自动执行,但是它在shouldComponentUpdate以后
// 如果shouldComponentUpdate返回true它才执行
// 如果返回false,这个函数就不会执行了
componentWillUpdate() {
console.log('componentWillUpdate');
}
// 组件更新完成以后,他会自动执行
componentDidUpdate() {
console.log('componentDidUpdate');
}
// 一个组件要从父组件接收参数
// 只要父组件的render函数被重新执行了,子组件的这个生命周期函数就会被执行
// 如果这个组件第一次存在于父组件中,不会执行
// 如果这个组件之前已经存在于父组件中,才会执行
componentWillReceiveProps() {
console.log('child componentWillReceiveProps');
}
(4)Unmounting
页面销毁的过程
// 当这个组件即将从页面中剔除的时候会被执行
componentWillUnmount() {
console.log('componentWillUnmount');
}
render 是生命周期函数
constructor 也是在某一个时刻自动调用执行的函数,但是我们不把它称为React的生命周期函数,因为它是es6的类语法,所以不被归类为React的生命周期函数,它在组件一创建的那一刻被自动的调用
二.React父子组件生命周期函数执行过程
三.生命周期函数使用场景
所有的生命周期函数都可以不存在,但是render生命周期函数必须存在,因为React组件继承自Component,Component内置了所有其他的生命周期函数的默认实现,唯独没有内置render函数的默认实现,这对于组件来说render函数必须要自己来定义的,不定义就会报错。