Sequence of componentWillMount calls in React.js

六眼飞鱼酱① 提交于 2019-12-07 03:28:43

问题


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.

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. 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? Or am I right in assuming that componentWillMount is called for the parent activity first and then for the children (unlike componentDidMount)?

Thanks!


回答1:


OK. so here goes. If you have a simple structure with a parent and 2 children like this:

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

Then the sequence of events firing will be:

  1. <Parent> componentWillMount()
  2. <Parent> render(), which starts to render children
  3. <Child> componentWillMount() of the first child
  4. <Child> render() of the first child
  5. <Child> componentWillMount() of the second child
  6. <Child> render() of the second child
  7. <Child> componentDidMount() of the first child (these will start only after the last render in the tree has run)
  8. <Child> componentDidMount() of the second child
  9. <Parent> componentDidMount() (this one will run only after its last child has run componentDidMount)

You can find a codepen example here.



来源:https://stackoverflow.com/questions/37121145/sequence-of-componentwillmount-calls-in-react-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!