【问题标题】:React life cycle methods won't fire, when calling React.Component<props,state>'s render() method调用 React.Component<props,state> 的 render() 方法时,React 生命周期方法不会触发
【发布时间】:2020-01-22 10:27:54
【问题描述】:

我有一个父 react 组件,它动态生成自定义子元素数组。父母的生命周期方法被正确触发。它的子元素生命周期方法不会被调用。我的问题是:为什么?

家长:

export default class Parent extends React.Component<IParentProps, IParentState> {
  public children: Array<IChild & React.Component> = new ArrayArray<IChild & React.Component>();

  constructor(props) {
    super(props);

    this.children.push(new Child({
      options: {}
    }));
    this.children.push(new Child({
      options: {}
    }));

    console.log('constructor(props)');
  }

  public componentWillMount() {
      // gets called
  }

  public render(): React.ReactElement<IParentProps> {
    return (
        <div>
            {this.children[this.state.currentStep].render()}
        </div>
    );
  }
}

孩子:

export default class Child extends React.Component<IChildProps, IChildState> implements IChild {
  //#region IStep implementation
  //#endregion

  constructor(props) {
    super(props);
  }

  public componentWillMount() {
      // won't get called, neither any other life cycle method, such as componentDidMount etc.
  }


  public render(): React.ReactElement<IChildProps> {
   // gets called
    return (
      <div>
        I am child
      </div>
    );
  }
}

有什么想法吗?

【问题讨论】:

  • 我从不在我的 react 类中使用 public 关键字,但我不知道这是否会改变这里的任何东西
  • 它是隐式公开的,如果你不指定的话。因此:它不会改变任何东西。

标签: reactjs typescript


【解决方案1】:

你不能像这样调用孩子的渲染方法(/!\不好的做法)。 React 无法知道这个组件的存在。 这是一个修复:

export default class Parent extends React.Component<IParentProps, IParentState> {
  public children: Array<IChild & React.Component> = new ArrayArray<IChild & React.Component>();

  constructor(props) {
    super(props);

    this.children.push(new Child({
      options: {}
    }));
    this.children.push(new Child({
      options: {}
    }));

    console.log('constructor(props)');
  }

  public componentWillMount() {
      // gets called
  }

  public render(): React.ReactElement<IParentProps> {
    const Child = this.children[this.state.currentStep]
    return (
        <div>
            <Child />
        </div>
    );
  }
}

【讨论】:

  • 非常感谢,潘德利斯回答中的评论也是针对你的!
【解决方案2】:

您不应该直接调用render。

您需要改为通过React.createElement 使用 Reacts 安装和管理

如何实现的示例:

render(): React.ReactElement<IParentProps> {
    return (
        <div>
            {React.createElement(this.children[this.state.currentStep], props, children)}
        </div>
    );
  }

【讨论】:

  • 啊,我有一种感觉,调用 render() 会是一件“坏”的事情,但不知道更好的(最佳)做法会是什么。在前端世界中作为后端开发人员的生活很艰难。谢谢! :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-26
  • 2018-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-02
相关资源
最近更新 更多