在所有子组件之后,是否调用了父组件的 Component entDidMount?

我有下面的代码,在我的渲染的父

<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>

我认为只有在加载了所有子元素之后才会调用父元素的组件 DidMount。但是在这里,父组件的组件 DidMount 在子组件的组件 DidMount 之前被调用。

事情就是这样的吗? 还是我做错了什么。

如果是这样工作的,那么当所有子组件都从父组件加载时,我将如何检测?

30331 次浏览

UPDATE

This answer is for React 15. the current version is 17+ so this is potentially irrelevant.

ORIGINAL

Yes the componentDidMount of children are called before the parent.

Run the code below!

documentation states:

Invoked once, only on the client (not on the server), immediately after the initial rendering occurs. At this point in the lifecycle, you can access any refs to your children (e.g., to access the underlying DOM representation). The componentDidMount() method of child components is invoked before that of parent components.

This is because at time of rendering, you should be able to reference any internal/child nodes, attempting to access parent nodes is not accepted.

Run the code below. It shows the console output.

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>