react-router4 Prompt 路由拦截组件

首先由来:页面跳转后弹出提示,未保存时候要保存后跳转?图片如下

 

经过查阅资料发现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;

 

posted @ 2021-01-18 14:18  程序員劝退师  阅读(868)  评论(0编辑  收藏  举报