import { Prompt } from 'react-router'
import { Modal} from 'antd';
useEffect(() => {
localStorage.setItem('isPrompt', true);// 离开
}, []);
<Prompt
message={(location) => {
if (localStorage.getItem('isPrompt')=='false') {
return true;
} else {
Modal.confirm({
title: '确认离开吗?',
content: '需要关闭',
okText: '关闭',
cancelText: '取消',
onOk() {
//操作等等
localStorage.setItem('isPrompt', false);
props.history.push({
pathname: `..${location.pathname}`,
})
},
onCancel() {
console.log('Cancel');
},
});
return false;
} }
}
/>
react 离开当前页面拦截自定义。
用localStorage来存储主要是因为使用useState()有奇怪的bug,点击 确认 后使用hook更新 isPrompt 的值似乎不能立即变值,导致会弹出两次Modal,不知道啥原因。。。想念angular了。。。