在我的组件中,我尝试将接收到的道具与当前状态同步,以便从外部可见(我知道这是一种反模式,但我还没有找到另一种解决方案。我非常愿意接受建议!)。
无论如何,这就是我所拥有的:
export class PopupContainer extends React.Component {
state = {
show: false,
};
shouldComponentUpdate(nextProps, nextState) {
if (this.props.show === nextProps.show) return true;
return true;
}
componentDidUpdate(prevProps, prevState, snapshot) {
// if popup shown, fade it out in 500ms
if (this.props.show !== prevProps.show)
this.setState({ show: this.props.show });
if (this.state.show) {
setTimeout(() => this.setState({ show: false }), 2000);
}
}
render() {
return <Popup {...{ ...this.props, show: this.state.show }} />;
}
}
Run Code Online (Sandbox Code Playgroud)
在我的外部组件中,我正在渲染容器:
<PopupContainer
show={this.state.popup.show}
message={this.state.popup.message}
level={this.state.popup.level}
/>
Run Code Online (Sandbox Code Playgroud)
现在,当我最初设置this.state.show它 …