![](/img/trans.png)
[英]What is the purpose of having functions like componentWillMount in React.js?
[英]Sequence of componentWillMount calls in React.js
根据这个页面http://busypeoples.github.io/post/react-component-lifecycle/组件的渲染方法在componentWillMount
和componentDidMount
方法之间的其他地方被调用。
但是这里的组件生命周期的 react.js 文档https://facebook.github.io/react/docs/component-specs.html说所有子活动的componentDidMount
方法都在父活动之前调用。 我可以理解在渲染任何子组件之后调用componentDidMount
是可以的,但是运行时如何知道在渲染之前调用componentWillMount
函数的哪些子级? 或者我假设componentWillMount
首先为父活动调用,然后为子活动调用(与componentDidMount
不同)是否正确?
谢谢!
好的。 所以在这里。 如果你有一个简单的结构,有一个父级和 2 个子级,如下所示:
<Parent>
<Child/>
<Child/>
</Parent>
那么事件触发的顺序将是:
<Parent> componentWillMount()
<Parent> render()
,它开始渲染孩子<Child> componentWillMount()
第一个孩子<Child> render()
第一个孩子<Child> componentWillMount()
第二个孩子的<Child> componentWillMount()
<Child> render()
第二个孩子的<Child> render()
<Child> componentDidMount()
第一个孩子(这些只会在树中的最后一个渲染运行后启动)<Child> componentDidMount()
第二个孩子的<Child> componentDidMount()
<Parent> componentDidMount()
(这个只有在它的最后一个孩子运行componentDidMount
后才会运行)您可以在此处找到codepen 示例。
您可以在每个方法中放入console.log()
,以查看其在控制台中打印的顺序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.