1

私はReact ParentChildコンポーネントを持っています。子は、親コンポーネントの状態を更新できる必要があります。しかし、私はParent is unmountedいつ、Child 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
  );
}
4

1 に答える 1

0
  • 理由: React ライフサイクルによると、ComponentDidMount (_isMounted = true) の前に子コンポーネントがレンダリングされます。したがって、 setTitle props の this._isMounted 変数は常に = false => バグだと思います。

  • 解決策: setTitle props を渡した後、クラスでコールバック関数を作成することをお勧めします。

于 2020-10-19T10:46:32.527 に答える