React v17 生命周期

类组件

挂载时顺序

constructor()
static getDerivedStateFromProps(props, state)
render()
componentDidMount()

更新时顺序

static getDerivedStateFromProps(props, state)
shouldComponentUpdate()
render()
static getSnapshotBeforeUpdate(prevProps, prevState)
componentDidUpdate()

卸载

componentWillUnmount()

现版本废弃的生命周期钩子函数

image.png

componentWillMount
componentWillUpdate
componentWillReceiveProps
共同点
都处于 render 阶段

1、使用废弃的生命周期钩子函数可能造成的问题

完全可以转移到 componentDid(xxx) 中去做 。在 willMount 里发异步请求,能让数据得到的快些。但是,componentWillMount 结束后,render 会迅速地被触发,所以说首次渲染依然会在数据返回之前执行。这样做不仅没有达到你预想的目的,还会导致服务端渲染场景下的冗余请求等额外问题,得不偿失。

2、在 Fiber 带来的异步渲染机制下,可能会导致非常严重的 Bug

假如你在 componentWillxxx 里发起了一个付款请求。由于 render 阶段里的生命周期都可以重复执行,在 componentWillxxx 被打断 + 重启多次后,就会发出多个付款请求。
或者你可能会习惯在 componentWillReceiveProps(在已挂载的组件接收新的 props 之前被调用) 里操作 DOM(比如说删除符合某个特征的元素),那么 componentWillReceiveProps 若是执行了两次,你可能就会一口气删掉两个符合该特征的元素。

3、在 componentWillReceiveProps 和 componentWillUpdate 里滥用 setState 导致重复渲染死循环的

你可能感兴趣的:(React v17 生命周期)