React阻⽌路由离开(路由拦截)阻⽌React router跳转:
1、React不像Vue那样有router.beforeEach这样的路由钩⼦,但是它提供了⼀个组件:Prompt
import { Prompt } from 'react-router-dom';
<Prompt
when={true}
message={location => '信息还没保存,确定离开吗?'}
/>
在React跳转路由的时候,Prompt就会触发
2、我们可⽤withrouter把histroy注⼊props,⽤history.block
let isNeedBlock = true;
const unBlock = props.history.block(() => {
if (isNeedBlock) {
return '信息还没保存,确定离开吗?';
}
return unBlock();
});
阻⽌页⾯关闭、刷新
但是这个没法阻⽌刷新和关闭,这个时候我们⽤beforeunload事件
class Test extends React.Component {
componentDidMount() {
this.init();
window.addEventListener('beforeunload', this.beforeunload);
}
componentWillUnmount = () => {
};
react router v5beforeunload = (ev: any) => {
if (ev) {
  ev.returnValue = '';
}
};
render() {
return <div>...</div>
}
}