React:render() 之后和子构造函数之前的函数调用

mas*_*ick 3 reactjs react-lifecycle react-component

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

<Parent>
  <Child/>
</Parent>
Run Code Online (Sandbox Code Playgroud)

所以生命周期如下:

  1. 父构造函数
  2. 父母的渲染()
  3. 子构造函数
  4. 孩子的渲染()
  5. 孩子已安装
  6. 父级已挂载

我可以在第 2 步之后和第 3 步之前以某种方式进行额外的父初始化吗?

更新:

<Parent>
  <Child/>
</Parent>
Run Code Online (Sandbox Code Playgroud)
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"));
Run Code Online (Sandbox Code Playgroud)

在这里我做了一些简化——我不仅仅是改变元素的颜色,我可以在componentDidMount()方法中做到这一点。相反,ThirdPartyLib细节决定了初始化顺序。在创建任何子元素之前,我必须在它出现在 DOM 中之后立即初始化它。

更具体地说,Parent并Child共享ThirdPartyLib该类的完全相同的实例。我无法将初始化逻辑放入 Parent 的render()函数中,因为该元素尚未在 DOM 中。同样,我无法按照 via 注释中的建议初始化Parentbefore ,因为's在's之前执行。ChildcomponentDidMount()ChildcomponentDidMount()Parent

Rya*_*ell 6

解决此问题的一种方法是延迟渲染子项,直到安装父项之后。步骤如下:

  • 初始父级渲染不渲染子级(例如,在父级状态下使用标志抑制)
  • ParentcomponentDidMount执行第三方初始化并更改 Parent 状态中的标志触发父级的重新渲染
  • 重新渲染 Parent 现在将渲染 Child 并且 Parent 可以通过 prop 将第三方初始化信息传递给 Child

生成的代码类似于:

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);
Run Code Online (Sandbox Code Playgroud)

编辑 82q69v3469