【发布时间】:2021-02-02 02:44:21
【问题描述】:
我有一个 React Parent 和 Child 组件。 Child 必须能够更新 Parent 组件的状态。但是,我的Parent is unmounted 当Child 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