反应:在render()之后和子级的constructor()之前的函数调用

时间:2019-01-16 14:35:31

标签: reactjs react-component react-lifecycle

我有一个名为 Parent 的组件,其中还有一个名为 Child 的组件:

<Parent>
  <Child/>
</Parent>

因此生命周期如下:

  1. 父级构造函数
  2. 父母的render()
  3. 子构造函数
  4. 孩子的render()
  5. 孩子已上架
  6. 父级已安装

我可以在第2步之后到第3步之前做其他的Parent初始化吗?

更新:

class ThirdPartyLib {
  init(elementId) {
    console.log(`initializing element: ${elementId}`);
    // element with #id: elementId should exist!
    // document.getElementById(elementId).style.color = "red";
  }
}

class Parent extends React.Component {
    constructor(props) {
        super(props);
        console.log("Parent's constructor");
    }

    render() {
        console.log("rendering Parent");
        new ThirdPartyLib().init("parent");
        return (
            <div id="parent">Parent: {this.props.name}
                <Child name="Sara"/>
            </div>
        );
    }

    componentDidMount() {
        console.log("Parent is mounted");
    }
}

class Child extends React.Component {
    constructor(props) {
        super(props);
        console.log(`Child ${this.props.name} constructor`);
    }

    render() {
        console.log(`rendering Child: ${this.props.name}`);
        return <div>Child: {this.props.name}</div>
    }

    componentDidMount() {
        console.log(`Child ${this.props.name} is mounted`);
    }
}

ReactDOM.render(<Parent name="Bob"/>, document.getElementById("app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>


<div id="app"></div>

在这里,我做了一些简化-我不仅在更改元素的颜色,还可以通过componentDidMount()方法进行更改。相反,ThirdPartyLib的详细信息规定了初始化顺序。我必须在父元素出现在DOM中之后,创建任何子元素之前立即对其进行初始化。

更具体地说,ParentChild共享ThirdPartyLib类的完全相同的实例。我不能将初始化逻辑放入Parent的render()函数中,因为该元素还不在DOM中。同样,我无法按照Parent的注释中的建议在Child之前初始化componentDidMount(),因为Child的{​​{1}}在{{ 1}}。

1 个答案:

答案 0 :(得分:2)

一种解决方法是将渲染子项延迟到挂载父项之后。步骤如下:

  • 初始父级渲染不会渲染子级(例如,禁止使用处于“父级”状态的标志)
  • 父母componentDidMount执行第三方初始化并在“父母”状态下更改标志,以触发父母的重新呈现
  • 重新渲染父级现在将渲染子级,父级可以通过道具将第三方初始化信息传递给子级

结果代码如下:

import React from "react";
import ReactDOM from "react-dom";

class ThirdPartyLib {
  init(elementId) {
    console.log(`initializing element: ${elementId}`);
    this.element = document.getElementById(elementId);
    this.element.style.color = "red";
  }
}

class Parent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { initialized: false };
    console.log("Parent's constructor");
  }

  render() {
    console.log("rendering Parent");
    return (
      <div id="parent">
        Parent: {this.props.name}
        {this.state.initialized && (
          <Child name="Sara" thirdPartyLib={this.state.thirdPartyLib} />
        )}
      </div>
    );
  }

  componentDidMount() {
    console.log("Parent is mounted");
    const thirdPartyLib = new ThirdPartyLib();
    thirdPartyLib.init("parent");
    this.setState({ initialized: true, thirdPartyLib });
  }
}

class Child extends React.Component {
  constructor(props) {
    super(props);
    console.log(`Child ${this.props.name} constructor`);
    console.log(
      `Child knows stuff from thirdPartyLib: ${
        this.props.thirdPartyLib.element.id
      }`
    );
  }

  render() {
    console.log(`rendering Child: ${this.props.name}`);
    return (
      <div>
        Child: {this.props.name}
        <br />
        ThirdPartyLib element id:
        {this.props.thirdPartyLib.element.id}
      </div>
    );
  }

  componentDidMount() {
    console.log(`Child ${this.props.name} is mounted`);
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<Parent name="Bob" />, rootElement);

Edit 82q69v3469