react 生命周期指的是组件从创建到卸载的整个过程,每个过程都有对应的钩子函数会被调用,它主要有以下几个阶段:
下文分别从上述三个阶段解读react的生命周期

componentWillMount - render - componentDidMountcomponentWillReceiveProps - shouldComponentUpdate - componentWillUpdate - render - componentDidUpdatecomponentWillUnmountcomponentWillMount发生在render之前,此时还没有挂载DOM,有可能会被执行多次
常用的钩子,在组件挂载成功之后调用,该过程组件已经成功挂载到了真实 DOM 上。
一般在这个钩子中做一些初始化的事,例如:开启定时器、发送网络请求、订阅消息
componentDidMount(){
fetch('https://api.github.com/users').then(res=>res.json()).then(users=>{
console.log(users);
this.setState({users});
});
}
在props发生改变(父组件重新render或者更新props)时调用,这个钩子提供对 props 的监听,在 props 发生改变后,相应改变组件的一些 state。在这个方法中改变 state 不会二次渲染,而是直接合并 state。
这个钩子相当于一个阀门,返回一个布尔值,决定是否更新组件。
由于 react 父组件更新,必然会导致子组件更新,因此我们可以在子组件中通过手动对比 props 与 nextProps,state 与 nextState 来确定是否需要重新渲染子组件,如果需要则返回true,不需要则返回 false。该函数默认返回 true。
组件更新前调用的钩子
组件更新完成后调用的钩子
this.props 和 nextProps 的前提下可以发送网络请求。componentDidUpdate(prevProps, prevState, snapshot) {
if (this.props.userID !== prevProps.userID) {
this.fetchData(this.props.userID);
}
}
卸载阶段唯一的生命周期钩子,通常在这里处理一些善后工作,例如关闭定时器、取消监听等等

react 打算在17版本推出新的 Async Rendering(异步渲染),提出一种可被打断的生命周期,而可以被打断的阶段正是实际 dom 挂载之前的虚拟 dom 构建阶段,也就是要被去掉的三个生命周期。
componentWillMount,componentWillReceiveProps,componentWillUpdatestatic getDerivedStateFromProps(nextProps, prevState),getSnapshotBeforeUpdate(prevProps, prevState)
getDerivedStateFromProps - render - componentDidMountgetDerivedStateFromProps - shouldComponentUpdate - render - getSnapShotBeforeUpdate - componentDidUpdatecomponentWillUnmount该生命周期在 render方法之前调用,在初始化和后续更新都会被调用
它接收两个参数,一个是传进来的 nextProps 和之前的 prevState。他应该返回一个对象来更新 state。如果返回 null 则不更新任何内容。
这个生命周期主要为我们提供了一个可以在组件实例化或 props、state 发生变化后根据 props 修改 state 的一个时机。
在更新阶段 render 后挂载到真实 DOM 前进行的操作,它使得组件能在发生更改之前从 DOM 中捕获一些信息。此组件返回的任何值将作为 componentDidUpdate 的第三个参数。
getSnapshotBeforeUpdate(prevProps, prevState){
return "getSnapshotBeforeUpdate";
}
// 组件更新成功钩子
componentDidUpdate(prevProps, prevState, snapshot) {
console.log(snapshot); // "getSnapshotBeforeUpdate"
}
constructorgetDerivedStateFromPropsrenderconstructorgetDerivedStateFromPropsrendercomponentDidMountcomponentDidMountgetDerivedStateFromPropsshouldComponentUpdaterendergetSnapShotBeforeUpdatecomponentDidUpdategetDerivedStateFromPropsshouldComponentUpdaterendergetDerivedStateFromPropsshouldComponentUpdaterendergetSnapShotBeforeUpdategetSnapShotBeforeUpdatecomponentDidUpdatecomponentDidUpdategetDerivedStateFromPropsshouldComponentUpdaterendergetSnapShotBeforeUpdatecomponentWillUnmountcomponentDidUpdate