javascript - parent 的 componentDidMount 是在所有 children 的 componentDidMount 之后调用的吗?

标签 javascript reactjs

我的父渲染中有下面的代码

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

我以为parent的componentDidMount只有在所有childs都加载后才会被调用。但是这里parent的componentDidMount是在child的componentDidMount之前调用的。

这是事情的运作方式吗?还是我做错了什么。

如果这是工作原理,我如何检测所有子组件何时从父组件加载?

最佳答案

更新

此答案适用于 React 15。当前版本为 17+,因此这可能无关紧要。

原创

是的,子级的 componentDidMount 在父级之前被调用。

运行下面的代码!

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.

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

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

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>

关于javascript - parent 的 componentDidMount 是在所有 children 的 componentDidMount 之后调用的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32814970/

相关文章:

javascript - React 组件没有函数或类?

javascript - React - 如何渲染嵌套组件而不是 [object Object]?

javascript - react promise - TypeError : Cannot read property 'then' of undefined

javascript - Google Closure 编译器 100% 输入

javascript - 将标题文本添加到 d3 中的路径中心

javascript - 如何在 javascript 中使用递归来创建键值对象

javascript - 模拟非 http url 的 .click()

javascript - jQuery - 图片捕捉到错误的位置

javascript - 类型错误 : Cannot read property 'firstName' of undefined - using 'props' in react

reactjs - 无法从react js访问httponly cookie,但可以在 postman 应用程序中访问!这怎么可能?