Does componentDidUpdate run after all children have been updated?

前端 未结 3 1244
一整个雨季
一整个雨季 2020-12-31 04:18

I would like to know if a React component\'s lifecycle method componentDidUpdate gets executed after all of the children\'s render methods have fin

3条回答
  •  星月不相逢
    2020-12-31 04:34

    Not sure if there is more in-depth documentation somewhere, but it is indeed easy enough to test on your own.

    class Nested extends React.Component {
      constructor(props){
        super(props);
        this.state = {foo: undefined};
      }
      render() {
        console.log("Rendered " + this.props.name);
        return 
    {this.props.children ? React.cloneElement(React.Children.only(this.props.children), {foo: this.state.foo}) : undefined}
    } componentDidUpdate() { console.log("Updated " + this.props.name); } } ReactDOM.render(, document.getElementById("app"));

    http://jsbin.com/yiyuhegayo/edit?js,console,output

    Updating the outer component results in the innermost componentDidUpdate running first, and then the outermost. Updating the inner component only causes that component to update.

    Interestingly, it is the opposite for the render functions. The outer component renders first, then the inner one.

提交回复
热议问题