React父母为孩子卸货了吗?

问题描述

我有一个React ParentChild组件。子级必须能够更新父级组件的状态。但是,我的问题是我的Parent is unmountedChild wants to update the Parent的时候,我不确定为什么或如何解决此问题?

我正在粘贴与该问题相关的简化代码在这种情况下,孩子想更新在page Title中呈现的Parent。但是可悲的是,在孩子的componentDidMount()(发生此更新的地方)中,父母已经是unmounted

index.js直接加载Child,但将Parent组件包裹在其周围。我想这与Parent组件的卸载有关吗?

父母:

type Props = TranslationProps & {
  Component: any
};
type State = {
  setTitle: string
};

export class Layout extends Component<Props,State> {
  _isMounted = false;

  constructor(props:Props) {
    super(props);

    this.state = {
      setTitle: ""
    };
  }

 componentDidMount() {
    this._isMounted = true;
  }

  componentwillUnmount() {
    this._isMounted = false;
  }

  render() {
    const { Component,...restProps } = this.props;

    return (
      <Component
        setTitle={title=> this._isMounted && this.setState({ setTitle: title})}
        isMounted={this._isMounted}
        {...restProps}
      />
    );
  }
}

孩子:

type Props = TranslationProps & {
  setTitle: (data: string) => void,isMounted: boolean
};

componentDidMount() {
    const { t } = this.props;
    if(this.props.isMounted) {
      this.props.setTitle("Test title");
    }
  }

索引:

const unwrap = component => {
  if(component.WrappedComponent) {
    return unwrap(component.WrappedComponent);
  }

  return component;
}

let reactMounts = document.querySelectorAll("[data-react]");
for (let reactMount of reactMounts) {
  let Component = Components[reactMount.dataset.react];
  let UnwrappedComponent = unwrap(Component);
  console.log("Rendering",Component," (",UnwrappedComponent,") to ",reactMount);

  let data = {
    ...reactMount.dataset,Component
  };
  delete data.react;

  render(
    React.createElement(Components['Layout'],data),reactMount
  );
}

解决方法

  • 原因:根据React生命周期,子组件在ComponentDidMount之前呈现(其中_isMounted = true)。因此,我猜setTitle道具中的this._isMounted变量总是= false =>错误。

  • 解决方案:我建议您在传递setTitle道具之后,在类中创建回调函数。