首页 > 其他 > 详细

React 阻止路由离开

时间:2020-06-29 13:22:14      阅读:169      评论:0      收藏:0      [点我收藏+]

React不像Vue那样有router.beforeEach这样的路由钩子,但是它提供了一个组件:Prompt

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

在React跳转路由的时候,Prompt就会触发

 

但是这个路由没法阻止刷新和关闭,这个时候我们用beforeunload事件

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>
    }
}

  

React 阻止路由离开

原文:https://www.cnblogs.com/amiezhang/p/13207409.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!