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