reactrouter是使用history对象进行页面跳转的,但是history对象在reactrouter初始化时提供了,我们在非组件中使用不了useHistory,有时我们遇到要在js文件中比如axios拦截器中使用history就会出问题,Router组件提供了一个prop为history,我们可以从history包中导出一个createBrowserHistory/createHashHistory方法创建我们的history对象,然后注入到Router上,这样在其它js文件中即可使用我们自己的history对象了
首先我们创建一个history.js文件用于初始化history对象,我这里使用的是browserhistory:
import { createBrowserHistory } from 'history' // 这个是cra自动装了的依赖 不用额外安装
export default createBrowserHistory() // 自己提供history解决组件外访问不到history无法使用的情况
然后在将history对象注入Router组件
import history from '@/utils/history'
import { Router } from 'react-router-dom'
<Router history={history}></Router>
然后我们就可以在其它js文件里导入我们自己创建的history对象即可使用