什么是生命周期函数?
生命周期函数是指在某一时刻,组件会自动调用执行的函数。
组件挂载(Mounting):
1、componentWillMount:在组件即将被挂载到页面的时刻被执行,且执行一次;
2、render:在组件挂载时被执行,并不负责渲染;
3、componentDidMount:在组件被挂载到页面之后被执行,且执行一次;
组件更新(Updation):
组件更新发生在props和states发生改变的情况下,数据发生变化时,页面的更新将被执行。
props和states发生变化时会执行的生命周期函数:
1、shouldComponentUpdate:组件被更新之前,该生命周期函数被执行,要求返回一个布尔类型的结果(组件是否需要更新,若return false,组件不被更新且后面的生命周期不被执行);
2、componentWillUpdate:组件被更新之前,shouldComponentUpdate之后,该函数被执行。如果shouldComponentUpdate返回false,该函数不被执行。
3、render:props 或 states 改变之后,会更新虚拟DOM,但并不负责渲染。
4、componentDidUpdate:组件更新完成之后,该函数被执行。
*5、componentWillReceiveProps:当一个组件从父组件接收参数,只要父组件的render函数被再次执行,子组件的componentWillReceiveProps函数就会被执行。需要注意的是,如果该子组件首次存在于父组件中则该函数不会被执行,只有当该子组件已经存在于父组件中且父组件render函数被执行,才会被执行。
组件卸载(Unmounting):
1、componentWillUnmount:当组件即将被从页面中卸载的时候,该函数被执行。
生命周期函数应用场景:
1、父子组件传值关于 render 的性能优化
由于父组件props、state发生改变时会触发父组件 render 生命周期,父组件触发 render 生命周期,也会触发子组件的render生命周期函数,因此可以在子组件shouldComponentUpdate生命周期函数上对props数据进行对比,当数据发生变化才触发render函数,在一定程度上优化性能。
shouldComponentUpdate(nextProps, nextState) {
if(nextProps.content !== this.props.content) {
return true
} else {
return false
}
}
2、数据请求写在 componentDidMount 里,页面挂载之后执行。