今天写代码时碰到一个让我疑惑的事情,就是 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
很像,现在已经修复了这个问题。真是让人醉醉的。