思路:创建可供组件外部使用的 history 对象
步骤:
- 创建
utils/history.ts,在里面创建一个 history 对象并导出 - 在
App.tsx中使用Router组件来替代BrowserRouter,并将外部 history 对象关联到Router上
utils/history.ts
import { createBrowserHistory } from 'history'
const history = createBrowserHistory()
export default history
App.tsx
import { Router, Redirect, Route } from 'react-router-dom'
import history from './utils/history'
<Router history={history}>
使用:
import history from './utils/history' // 导入history对象
history.push('/home') // 跳转路由