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