【问题标题】:React parent is unmounted for child?为孩子卸载反应父母?
【发布时间】:2021-02-02 02:44:21
【问题描述】:

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

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

【问题讨论】:

    标签: reactjs components parent mount unmount


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

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

    【讨论】:

    • 嗨——在课堂上创建回调函数是什么意思?那会在哪里?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-05
    相关资源
    最近更新 更多