如上图代码, 我们在拦截器里面不能直接使用history进行跳转,而用location.href直接复制会导致页面刷新,那么如何在非组件内直接使用history进行页面跳转?
参考代码:https://github.com/remix-run/react-router/blob/v5/packages/react-router-dom/modules/BrowserRouter.js
首先react-router-dom中直接有Router这个包,但是它Router 没有history属性,在安装react-router-dom时,默认会安装history包,我们可以通过这个包来自己创建history对象.
有如下公式:
Router + HashHistroy = HashRouter
Router + BrowerHistroy = BrowerRouter
根据上面公式可知:
单独引入Router,并自己创建history,(顺带直接导出)
import { Router, Route, Switch, Redirect } from 'react-router-dom'
import { createBrowserHistory } from 'history'
export const history = createBrowserHistory()
function App () {
return (
<Router history={history}>
// 为了能够在非组件环境下拿到路由信息,需要我们自定义 Router 的 history
手动模拟token失效:
同时在需要提高一个复用的情况也可以考虑进行封装.
示列代码:
// 自定义history对象
import { createBrowserHistory } from 'history'
const history = createBrowserHistory()
export default history
// 注意:此处,需要导入 Router 组件
import { Router } from 'react-router-dom'
import history from '@/utils/history'
function App() {
return (
<Router history={history}></Router>
)
}