【问题标题】:Is componentDidMount of parent called after all componentDidMount of children?在所有子组件的componentDidMount之后调用父组件的componentDidMount吗?
【发布时间】:2015-12-25 05:19:15
【问题描述】:

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

<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。但是这里 parent 的 componentDidMount 是在 child 的 componentDidMount 之前调用的。

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

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

【问题讨论】:

  • 子组件的componentDidMount()方法先于父组件调用Link.
  • 但是当我控制台登录父子组件DidMount()时。文本表单父母 console.log 首先打印
  • 它在小提琴中给出了正确的结果。可能是因为我在 parent 的 componentDidMount 中异步获取数据,并使用从调用返回的数组循环遍历子 OSMData 由 ajax 调用返回。
  • 是的,所以基本上你使用父级的componentDidMount() 进行一些操作(AJAX 或其他)在加载子组件之前。如果您的子组件已经在父组件中布局且不依赖外部数据,则子组件的 componentDidMount() 将在父组件之前调用。
  • 我也面临同样的问题。异步数据加载中断了我的 componentDidMount() 循环,因为首先显示了占位符。我想没有办法解决。也许重组我的组件...

标签: javascript reactjs


【解决方案1】:

更新

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

原创

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

运行下面的代码!

documentation states:

在初始渲染发生后立即在客户端(而不是服务器)上调用一次。在生命周期的这一点上,您可以访问您的孩子的任何 refs(例如,访问底层的 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>

【讨论】:

  • 您能否提供显示The componentDidMount() method of child components is invoked before that of parent components 的链接,我在反应站点中找不到它。
  • 这似乎不再出现在文档中,因为我在componentDidMount 上看到的唯一官方文档在这里:facebook.github.io/react/docs/…
  • 更正它是在旧版本的文档中github.com/facebook/react/blob/v15.0.1/docs/docs/…
  • @DaveCole 我认为 componentWillMount() 现在已弃用。
猜你喜欢
  • 2017-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-08
  • 2017-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多