React 阻止路由離開(路由攔截)


阻止React router跳轉:

1、React不像Vue那樣有router.beforeEach這樣的路由鈎子,但是它提供了一個組件:Prompt

import { Prompt } from 'react-router-dom';
<Prompt
    when={true}
    message={location => '信息還沒保存,確定離開嗎?'}
/>

在React跳轉路由的時候,Prompt就會觸發

2、我們可用withrouter把histroy注入props,用history.block

let isNeedBlock = true; 
const unBlock = props.history.block(() => {
    if (isNeedBlock) {
          return '信息還沒保存,確定離開嗎?';
    }
    return unBlock();
});

 

 

 阻止頁面關閉、刷新

但是這個沒法阻止刷新和關閉,這個時候我們用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>
    }
}

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM