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

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>

}

}

  

以上是 React 阻止路由离开(路由拦截) 的全部内容, 来源链接: utcz.com/z/384022.html

回到顶部