父级的componentDidMount是否在子级的所有componentDidMount之后调用?


77

我父母的渲染中有以下代码

<div>           
{
    this.state.OSMData.map(function(item, index) {
        return <Chart key={index} feature={item} ref="charts" />
    })
}
</div>

以及下面我孩子图表中的代码

<div className="all-charts">
    <ChartistGraph data={chartData} type="Line" options={options} />
</div>

我以为父级的componentDidMount仅在加载所有子级后才被调用。但是这里,父级的componentDidMount在子级的componentDidMount之前被调用。

这是工作方式吗?还是我做错了什么。

如果这是工作方式,我如何检测从父级加载所有子级组件的时间?


12
componentDidMount()子组件的方法在父组件的方法之前调用Link
塔希尔·艾哈迈德

1
但是当我在父和子componentDidMount()中都进行console.log时。文本形式的父母的console.log是第一印刷
Aakash Sigdel

它在提琴中给出正确的结果。可能是因为我要在父对象的componentDidMount中异步获取数据,并使用从调用返回的数组来遍历子OSMData是由ajax调用返回的。
Aakash Sigdel

是的,因此,基本上,您加载子组件之前使用了父组件的componentDidMount()一些操作(AJAX或其他方法)。如果您的子组件已经放置在父组件中,而又不依赖于外部数据,那么子组件将在父组件之前被调用。componentDidMount()
塔希尔·艾哈迈德

我正面临着同样的问题。异步数据加载中断了我的componentDidMount()周期,因为首先显示了一个占位符。我想没有办法解决。也许是重组我的组件……
larrydahooster's

Answers:


67

是的componentDidMount,孩子的名字在父母之前被称为。

运行下面的代码!

文档状态

初始渲染发生后立即仅在客户端(而不是服务器)上调用一次。在生命周期的这一点上,您可以访问子代的任何引用(例如,访问基础的DOM表示形式)。子组件componentDidMount()方法在父组件的方法之前被调用。

这是因为在渲染时,您应该能够引用任何内部/子节点,并且不尝试访问父节点。

运行下面的代码。它显示控制台输出。

var ChildThing = React.createClass({
  componentDidMount: function(){console.log('child mount')},
  render: function() {
    return <div>Hello {this.props.name}</div>;
  }
});

var Parent = React.createClass({
  componentDidMount: function(){console.log('parent')},
  render: function() {
    return <div>Sup, child{this.props.children}</div>;
  }
});

var App = React.createClass({
  componentDidMount: function(){console.log('app')},
  render: function() {
    return (
      <div>
        <Parent>
          <ChildThing name="World" />
        </Parent>
      </div>
    );
  }
});

ReactDOM.render(
  <App />,
  document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="container">
    <!-- This element's contents will be replaced with your component. -->
</div>


1
您能否提供表示的链接The componentDidMount() method of child components is invoked before that of parent components,我在React网站中找不到它。
Hendra Uzia

这似乎并没有出现在文档了,因为唯一的官方文档香港专业教育学院看到componentDidMount在这里:facebook.github.io/react/docs/...
克里斯·W·


父级的FWIW componentWillMount()将在子级的componentWillMount()或componentDidMount()例程中被调用,因此您可以在此处执行任何需要在那里准备好的代码。甚至更疯狂的是,即使您的父渲染中有如下语句:{codeThatNeedsToBeRunFirstBoolean?<mycomponent />:null}并且codeThatNeedsToBeRunFirstBoolean为false,仍然会调用mycompoment上的componentDidMount()。
戴夫·科尔
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.