繁体   English   中英

React.js 中的 componentWillMount 调用顺序

[英]Sequence of componentWillMount calls in React.js

根据这个页面http://busypeoples.github.io/post/react-component-lifecycle/组件的渲染方法在componentWillMountcomponentDidMount方法之间的其他地方被调用。

但是这里的组件生命周期的 react.js 文档https://facebook.github.io/react/docs/component-specs.html说所有子活动的componentDidMount方法都在父活动之前调用。 我可以理解在渲染任何子组件之后调用componentDidMount是可以的,但是运行时如何知道在渲染之前调用componentWillMount函数的哪些子级? 或者我假设componentWillMount首先为父活动调用,然后为子活动调用(与componentDidMount不同)是否正确?

谢谢!

好的。 所以在这里。 如果你有一个简单的结构,有一个父级和 2 个子级,如下所示:

<Parent>
  <Child/>
  <Child/>
</Parent>

那么事件触发的顺序将是:

  1. <Parent> componentWillMount()
  2. <Parent> render() ,它开始渲染孩子
  3. <Child> componentWillMount()第一个孩子
  4. <Child> render()第一个孩子
  5. <Child> componentWillMount()第二个孩子的<Child> componentWillMount()
  6. <Child> render()第二个孩子的<Child> render()
  7. <Child> componentDidMount()第一个孩子(这些只会在树中的最后一个渲染运行后启动)
  8. <Child> componentDidMount()第二个孩子的<Child> componentDidMount()
  9. <Parent> componentDidMount() (这个只有在它的最后一个孩子运行componentDidMount后才会运行)

您可以在此处找到codepen 示例

您可以在每个方法中放入console.log() ,以查看其在控制台中打印的顺序。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM