以前面试过一些大厂,面试官对react的生命周期的知识点问来问去,问的都不知道react仍是本身内心的那个react了吗?在使用过程当中还要这么多套路吗?
首先看下官方给出React16.4
生命周期图
html
官方地址连接: 生命周期
看完这个图,脑子有没有清楚些?能够看下面来加深印象react
我选择的是使用
create-react-app
建立的项目,
你们也可使用
codesandbox
,
地址:
codesandbox.io/s/wizardly-…
成功建立项目启动后开始实践吧!
面试
插播广告:是否是感受这个项目的绿色和以前的蓝色不同了,可使用
npx create-react-app project
建立最新的项目试一试哦!
插播知识点:
getDerivedStateFromProps
会在调用 render 方法以前调用,而且在初始挂载及后续更新时都会被调用。它应返回一个对象来更新 state,若是返回 null 则不更新任何内容。
getSnapshotBeforeUpdate()
在最近一次渲染输出(提交到 DOM 节点)以前调用。它使得组件能在发生更改以前从 DOM 中捕获一些信息(例如,滚动位置)。今生命周期的任何返回值将做为参数传递给componentDidUpdate()
。
bash每一个生命周期详细介绍:app
根据理解的思路咱们分为几个假设来进行ui
测试这个流程,咱们把全部的生命周期罗列起来并打印全部的生命周期。this
而后发现报了一堆警告⚠️从上到下说下第一个spa
仍是这三个生命周期的警告⚠️因为即将删除这三个生命周期咱们在使用的过程当中须要在生命周期前加UNSAFE_
例如 :UNSAFE_componentWillMount
3d
为了正常进行,咱们须要注释先注释掉getDerivedStateFromProps
getSnapshotBeforeUpdate
并给三个即将废弃的生命周期加上UNSAFE_
在运行
constructor ->UNSAFE_componentWillMount-> render -> componentDidMount
constructor -> getDerivedStateFromProps -> render -> componentDidMount
测试流程:声明一个newState默认值为0
this.state = {
newState: 0
};
changeState = () => {
this.setState({
newState: 1
})
}
复制代码
经过按钮改变newState值
<button onClick={this.changeState}>修改state</button>复制代码
建立一个组件Unmount
在App
中引用
//app组件
<Unmount newState={this.state.newState} />
class Unmount extends Component {
//此处用componentDidMount作表明,测试销毁组件是否执行这个生命周期
componentDidMount() {
console.log("Unmount -> componentDidMount")
}
componentWillUnmount() {
console.log("Unmount -> componentWillUnmount")
}
UNSAFE_componentWillReceiveProps(nextProps) {
console.log("Unmount -> UNSAFE_componentWillReceiveProps", nextProps)
}
render() {
return (
<div>Unmount</div>
);
}
}
复制代码
插播广告:若是shouldComponentUpdate
的结果return false
则生命周期只执行
getDerivedStateFromProps -> shouldComponentUpdate ->❌(结束)
测试流程:当App
中state<2
时销毁组件Unmount
//App组件
changeState = () => {
this.setState({
newState: this.state.newState + 1
})
}
{this.state.newState < 2 ? <Unmount /> : null}
复制代码
根据实践返回到咱们刚开始看到的声明周期执行顺序对比一下,有木有更清晰