react阻止页面刷新或者切换页面
1.引入Prompt
import { Prompt } from 'react-router-dom';
2.给页面绑定函数
function beforeunload(ev) {
if (ev) {
ev.returnValue = '';
}
}
useEffect(() => {
window.addEventListener('beforeunload', beforeunload)
return () => {
window.removeEventListener('beforeunload', beforeunload)
};
}, []);
3.使用
<Prompt
when={isSavex}
message={location => '信息还没保存,确定离开吗?'}
/>
4.效果
5.说明,Prompt的when为true的时候一直显示这个提示,为false不显示,自行根据业务逻辑修改