Is componentDidMount of parent called after all componentDidMount of children?

前端 未结 1 938
小蘑菇
小蘑菇 2020-11-30 02:51

I have the code below in my render of parent

{ this.state.OSMData.map(function(item, index) { return
相关标签:
1条回答
  • 2020-11-30 03:17

    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>

    0 讨论(0)
提交回复
热议问题