react开发中需要一些离开页面时的弹框提示,在一些既定的情况下,不像vue的路由拦截(beforeEach,beforeRouteLeave)那么方便
但是总需要去实现一些类似的功能,这样就可以使用react-router-dom v5的 Prompt,
还有一些类似 history.block()的函数暂时没有使用过,先写落地的吧
import React, { useState } from 'react';
import { Prompt, useHistory } from 'react-router-dom';
import { Modal } from 'antd';
import { useTranslation } from 'react-i18next';
interface PagePromptProps {
baseUrl: string;
}
const PagePrompt = React.forwardRef((props: PagePromptProps) => {
const { baseUrl } = props;
const { t } = useTranslation();
//页面跳转方法
const history = useHistory();
const [intercept, setIntercept] = useState(true); //开关 控制是否需要开启拦截
// 拦截的路由
const handleLeave = (e) => {
if (history.location.pathname === baseUrl) { //比对url,只有进入当前url才进行弹框
//只有新增的情况下才去判断菜单切换的问题,审批路由直接通过
if (history.location.pathname === e.pathname) {
return true;
} else {
setIntercept(false);
Modal.confirm({
title: t('您确定要放弃保存吗'),
className: 'purchase-modal',
okText: t('确定'),
cancelText: t('取消'),
onCancel: () => {
return false;
},
onOk: () => {
history.push(e.pathname);
return false;
}
});
return false;
}
} else {
return true;
}
};
return <Prompt when={intercept} message={handleLeave} />;
});
export default PagePrompt;
页面调用
import PagePrompt from '@/pages/components/PagePrompt';
<PagePrompt baseUrl={'/business/coaApply/profitCenter/create'} />
主要是为了方便,因此封装个公共的组件,这种可以监听页面表单的变化与否来做出对应得弹框,也可以直接使用,我这里主要是做了 离开当前的页面就进行逻辑处理;可根绝自己的对应逻辑来去优化