Bugfix for getDerivedStateFromProps

今天写代码时碰到一个让我疑惑的事情,就是 React 的 getDerivedStateFromProps 在我使用 setState 更新组件时竟然也会触发。吓得我以为是 React 的 bug,赶紧上网搜一下,结果好家伙。原来我一直理解错了这个生命周期函数。我还以为只有组件的父组件更新,触发了当前组件的 props 更新,然后才会触发 getDerivedStateFromProps

getDerivedStateFromProps is now called every time a component is rendered, regardless of the cause of the update. Previously, it was only called if the component was re-rendered by its parent, and would not fire as the result of a local setState. This was an oversight in the initial implementation that has now been corrected. The previous behavior was more similar to componentWillReceiveProps, but the improved behavior ensures compatibility with React’s upcoming asynchronous rendering mode.

直到我在官网上看到这样的一篇博客,让我很郁闷,16.4 版本以前,React 的开发者疏忽了这一块,然后导致这个方法确实只有在父组件更新时触发,和之前的 componentWillReceiveProps 很像,现在已经修复了这个问题。真是让人醉醉的。

转载于:https://my.oschina.net/u/3117745/blog/2980400

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值