前言
本来按照我的学习理念,学新不学旧,还可以减少记忆负担,但无奈听说面试都喜欢问react的新旧生命周期问题,只能都记录一下了。淦!
旧生命周期
先上完整生命周期图(图片来源尚硅谷免费课程): ![在这里插入图片描述](https://img-blog.csdnimg.cn/20210713213159633.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3BhZ256b25n,size_16,color_FFFFFF,t_70)
挂载阶段
react组件在挂载阶段,先会执行类定义里的constructor 构造器,初始化阶段:
constructor(props) {
super(props);
this.state = { count: 0 };
}
然后进入render 钩子,渲染阶段:
render() {
const { count } = this.state;
return (
<div>
{count}
</div>
);
}
接着进入componentDidMount 钩子,组件已挂载阶段:
componentDidMount() {
}
更新阶段
状态更新
从this.setState() 触发开始,先进入shouldComponentUpdate() 钩子,控制组件更新的“阀门”:
shouldComponentUpdate() {
return true;
}
然后进入componentWillUpdate() 钩子,组件将要更新:
componentWillUpdate() {}
然后进入render() 钩子,再进入componentDidUpdate()钩子,组件更新完成:
componentDidUpdate() {}
强制更新
通过调用this.forceUpdate() ,不更改任何数据,强制更新,进入生命周期流程,结合上文加看图。
父组件更新
例如父组件中传给子组件显示的数据在父组件中发生了改变,子组件中进入生命周期流畅(看图),先进入componentWillReceiveProps() 钩子,组件接收新props:
componentWillReceiveProps(props) {
}
然走接下来的流程,结合上文看图。
卸载阶段
当组件将要卸载,会进入componentWillUnmount 钩子函数,一般会用于清除一些定时器,实例,取消订阅消息等。例如:
componentWillUnmount() {
clearInterval(this.timer);
}
可以通过ReactDOM.unmountComponentAtNode(document.getElementById("")) 来强制卸载组件。
新生命周期
先上完整生命周期图(图片来源尚硅谷免费课程): ![在这里插入图片描述](https://img-blog.csdnimg.cn/2021071322465195.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3BhZ256b25n,size_16,color_FFFFFF,t_70) 总的来说就是即将废弃三个钩子函数componentWillReceiveProps() 、componentWillMount() 、componentWillUpdate() 。新增两个,下面讲解。
getDerivedStateFromProps
用处:若state的值在任何时候都取决于props,那么可以使用getDerivedStateFromProps() 。官方说尽量少用或不用,容易导致代码冗余。
static getDerivedStateFromProps(props, state) {
console.log("getDerivedStateFromProps", props, state);
return null;
}
getSnapshotBeforeUpdate
在即将更新视图的时候,像快门一样咔擦停住:
getSnapshotBeforeUpdate() {
return xxx
}
componentDidUpdate(preProps, preState, snapshotValue) {
console.log(
"Count---componentDidUpdate",
preProps,
preState,
snapshotValue
);
}
再结合图好好看看就能懂了~
|