简体   繁体   English

React.js 中的 componentWillMount 调用顺序

[英]Sequence of componentWillMount calls in React.js

According to this page http://busypeoples.github.io/post/react-component-lifecycle/ The render method for a component is called right in between the componentWillMount and componentDidMount methods amongst other places.根据这个页面http://busypeoples.github.io/post/react-component-lifecycle/组件的渲染方法在componentWillMountcomponentDidMount方法之间的其他地方被调用。

But the react.js documentation for component lifecycles here https://facebook.github.io/react/docs/component-specs.html says that the componentDidMount methods of all child activities are called before the parent.但是这里的组件生命周期的 react.js 文档https://facebook.github.io/react/docs/component-specs.html说所有子活动的componentDidMount方法都在父活动之前调用。 I can understand that componentDidMount is ok to call after any child components are rendered but how does the runtime know which children to call the componentWillMount function on before they are rendered?我可以理解在渲染任何子组件之后调用componentDidMount是可以的,但是运行时如何知道在渲染之前调用componentWillMount函数的哪些子级? Or am I right in assuming that componentWillMount is called for the parent activity first and then for the children (unlike componentDidMount )?或者我假设componentWillMount首先为父活动调用,然后为子活动调用(与componentDidMount不同)是否正确?

Thanks!谢谢!

OK.好的。 so here goes.所以在这里。 If you have a simple structure with a parent and 2 children like this:如果你有一个简单的结构,有一个父级和 2 个子级,如下所示:

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

Then the sequence of events firing will be:那么事件触发的顺序将是:

  1. <Parent> componentWillMount()
  2. <Parent> render() , which starts to render children <Parent> render() ,它开始渲染孩子
  3. <Child> componentWillMount() of the first child <Child> componentWillMount()第一个孩子
  4. <Child> render() of the first child <Child> render()第一个孩子
  5. <Child> componentWillMount() of the second child <Child> componentWillMount()第二个孩子的<Child> componentWillMount()
  6. <Child> render() of the second child <Child> render()第二个孩子的<Child> render()
  7. <Child> componentDidMount() of the first child (these will start only after the last render in the tree has run) <Child> componentDidMount()第一个孩子(这些只会在树中的最后一个渲染运行后启动)
  8. <Child> componentDidMount() of the second child <Child> componentDidMount()第二个孩子的<Child> componentDidMount()
  9. <Parent> componentDidMount() (this one will run only after its last child has run componentDidMount ) <Parent> componentDidMount() (这个只有在它的最后一个孩子运行componentDidMount后才会运行)

You can find a codepen example here .您可以在此处找到codepen 示例

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

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

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