我正在构建一个Redux应用程序.我希望用户确认是否要离开组件而不保存数据或取消转换并保存它然后离开. 例如,有没有办法阻止组件卸载? 如果您已经在使用react-router,则更好的方法是
例如,有没有办法阻止组件卸载?
如果您已经在使用react-router,则更好的方法是创建以下routerWillLeave挂钩.componentDidMount() {
this.props.router.setRouteLeaveHook(this.props.route, this.beforeUnload);
}
routerWillLeave(e) {
// check for a condition here
if (this.state.allowLeave === false) {
const message = 'Are you sure?';
(e || window.event).returnValue = message;
return message;
}
}
此外,要确保this.props.router可用,您必须将组件导出为:
export default withRouter(MyComponent);
请参阅https://github.com/reactjs/react-router/blob/master/docs/guides/ConfirmingNavigation.md的文档.
