首先由來:頁面跳轉后彈出提示,未保存時候要保存后跳轉?圖片如下

經過查閱資料發現react-router自帶組件Prompt可以進行路由攔截,來實現我們的功能,一共兩個參數
1、when:什么時候攔截路由
2、message:攔截提示信息,可以通過通過自定義方法實現功能;
查閱資料后,封裝成一個組件,如下所示:
import { Modal } from "antd";
import * as React from "react";
import { Prompt, useHistory } from "react-router";
interface IRouterPromptProps {
isBlock: boolean;
title?: string;
content?: string;
onOk?: () => void;
}
/**
* 路由攔截組件
* 監聽頁面跳轉是否需要保存信息
*/
export const RouterPrompt = React.memo((props: IRouterPromptProps) => {
const history = useHistory();
const [isBlock, setIsBlock] = React.useState(props.isBlock);
React.useEffect(() => {
setIsBlock(props.isBlock);
}, [props.isBlock])
const handleClick = (location: any, action: string, type: string) => {
setIsBlock(false);
if (props.onOk && type === 'ok') {
props.onOk();
}
setTimeout(() => {
if (action === 'POP') {
history.goBack();
} else if (action === 'PUSH') {
history.push(location);
} else {
history.replace(location);
}
}, 100);
}
return (
<Prompt
when={isBlock}
message={(location, action) => {
Modal.confirm({
title: props.title ? props.title : '信息還沒保存,確定離開嗎?',
content: props.content ? props.content : '',
okText: '確定',
cancelText: '取消',
onOk: () => handleClick(location, action, 'ok'),
onCancel: () => handleClick(location, action, 'cancel'),
})
return false;
}}
/>
)
});
export default RouterPrompt;
