React父项是否已为子项卸载



我有一个ReactParentChild组件。子组件必须能够更新父组件的状态。然而,我有一个问题,我的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
);
}
  • 原因:根据React生命周期,子组件在ComponentDidMount之前呈现(其中_isMounted=true(。所以,我猜是这样_setTitle props中的isMounted变量始终=false=>程序错误

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

最新更新