当我偶然发现这个时,我正在使用React LifeCycle方法:
我感到困惑,因为我看到render()函数运行2次。我所知道的是,React Life-Cycle中的任何功能只能运行一次。所以,为什么我在这里看到2个渲染函数(或运行2次)。这不会影响内存,并且不会第二次运行。
另外,我们如何知道渲染函数将在哪里运行(或在什么阶段运行),因为它可以在React Cycle中的2个地方运行。 Kinldy,请帮助澄清。
参考:
https://gist.github.com/bvaughn/923dffb2cd9504ee440791fade8db5f9
对于一个组件,render()
函数显然可以在同一安装中多次运行。您可以参考React文档中的this表。
从表中可以明显看出,如果安装了组件,则只有constructor
和componentDidMount
会运行一次(不包括componentWillUnmount
,在卸载该组件时它也会运行一次),而其他生命周期方法可以无限运行时间,取决于该组件的更新次数。
安装中
起初,Reactjs将只渲染一次方法,其生命周期将是:
constructor();
static getDerivedStateFromProps()
render();
componentDidMount();
更新中
但是更新时,component state or on receiving new props
将触发以下生命周期:
static getDerivedStateFromProps()
shouldComponentUpdate();
render();
getSnapshotBeforeUpdate();
componentDidUpdate();
不是,从shouldComponentUpdate()
返回false不会触发渲染
[C0以外的所有方法都是可选的