前奏
学习react的看官都知道,react生命周期函数贯穿于组件的初始化、挂载、更新、销毁的整个过程,可以说配合紧密,但随着react使用的深入,在业务开发中一些声明周期函数也带来了一些严重的问题,因此官方大大也很快做出了修正,废弃了几个容易造成严重问题的函数,并且给出来替代的函数。
react精益求精的“弃子”
1、componentWillMount
2、componentWillUpdate
3、componentWillReceiveProps
原因
在 componentWillMount进行异步请求,能使数据返回的更快。但,componentWillMount 结束后,render 会立刻被触发,但此时componentWillMount中的异步请求结果可能还未返回结果,一单结果返回会重新render,所以说即使在componentWillMount就进行了异步请求,在返回数据后又会重新render,这会导致服务端渲染场景下的冗余请求等额外问题,得不偿失。因此与在componentDidMount来请求没他大差别,所以官方将她废除。
假如你在 componentWillMount里发起了一个付款请求。由于 render 阶段里的生命周期都可以重复执行,在 componentWillMount被打断 + 重启多次后,就会发出多个付款请求。
或者你可能会习惯在 componentWillReceiveProps(在已挂载的组件接收新的 props 之前被调用) 里操作 DOM(比如说删除符合某个特征的元素),那么 componentWillReceiveProps 若是执行了两次,你可能就会一口气删掉两个符合该特征的元素。
假如在 componentWillReceiveProps 和 componentWillUpdate 里滥用 setState ,将导致重复渲染死循环。
新生命周期函数
constructor()
static getDerivedStateFromProps(props, state)
shouldComponentUpdate()
render()
componentDidMount()
static getSnapshotBeforeUpdate(prevProps, prevState)
componentDidUpdate()
componentWillUnmount()
挂载前顺序
constructor()
static getDerivedStateFromProps(props, state)
render()
挂在后
componentDidMount()
更新前顺序
static getDerivedStateFromProps(props, state)
shouldComponentUpdate()
render()
更新后顺序
static getSnapshotBeforeUpdate(prevProps, prevState)
componentDidUpdate()
卸载
componentWillUnmount()
最后
感谢简书问_道 https://www.jianshu.com/p/13b62e814a04 的文章帮助,让我对react生命周期函数有了更加深刻的理解。
万般皆下品,唯有读书高。