React.js 中的 componentWillMount 调用顺序

IT技术 javascript html facebook reactjs single-page-application
2021-05-24 19:07:57

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

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

谢谢!

1个回答

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

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

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

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

您可以在此处找到codepen 示例