React 阻止路由离开(路由拦截)

React 阻止路由离开(路由拦截)

admin
2021-03-10 / 0 评论 / 218 阅读 / 正在检测是否收录...

在业务开发中,我们经常会遇到用户操作页面,当用户做了修改时,需要在离开页面时警示用户保存数据的问题:
React不像Vue那样有 router.beforeEach 这样的路由钩子。在 React 中我们可以通过如下方式实现:
1、使用 react-router-dom 提供的 Prompt 组件

import { Prompt } from 'react-router-dom';
<Prompt
    when={hasModified}
    message={location => '信息还没保存,确定离开吗?'}
/>

在React跳转路由的时候,Prompt就会触发,当 hasModified 为 true 时就会弹窗提示用户是否确认离开,提示的内容就是 message 中的内容

2、我们还可用 histroy 的 block 函数拦截路由离开。

const unBlock = props.history.block(() => {
    if (hasModified) {
          return '信息还没保存,确定离开吗?';
    }
    return unBlock();
});

请输入图片描述

上面的两种方式都是基于 React 应用程序实现的,这两种方法没法阻止浏览器的刷新和关闭,这个时候我们需要用到 window 对象上的 beforeunload 事件来拦截刷新和关闭窗口的事件

class 组件中的使用

class Test extends React.Component {
    componentDidMount() {
        this.init();
        window.addEventListener('beforeunload', this.beforeunload);
    }

    componentWillUnmount = () => {
        window.removeEventListener('beforeunload', this.beforeunload);
    };

    beforeunload = (ev: any) => {
        if (ev) {
          ev.returnValue = '';
        }
    };

    render() {
        return <div>...</div>
    }
}

函数 hooks 组件中的使用

export default function(props: any) {
    beforeunload = (ev: any) => {
        if (ev) {
          ev.returnValue = '';
        }
    };

   useEffect(() => {
      window.addEventListener('beforeunload', beforeunload);
      return () => {
        window.removeEventListener('beforeunload', beforeunload);
      }
   });
   return <div>...</div>
    
}

或者使用使用三方 hook函数 处理,代码如下

import { useBeforeunload } from 'react-beforeunload';
useBeforeunload(() => {
  return hasModified ? '' : false;
});

请输入图片描述

0

评论 (0)

取消