React被废弃的三个生命周期函数及替代函数

前奏

学习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生命周期函数有了更加深刻的理解。

万般皆下品,唯有读书高。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

老猿阿浪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值