1

我有一个React ParentChild组件。Child 必须能够更新 Parent 组件的状态。但是,我遇到了问题,我Parent is unmountedChild wants to update the Parent知道为什么或如何解决这个问题?

我正在粘贴与该问题相关的简化代码。在这种情况下,孩子想要更新page TitleParent. 但可悲的是componentDidMount(),在 Child (发生此更新的地方)中, Parent 已经是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
  );
}
4

1 回答 1

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

  • 解决方案:我建议你应该在类中创建回调函数,然后传入 setTitle 属性。

于 2020-10-19T10:46:32.527 回答