方法一:创建utils/history.ts
,
import { createBrowserHistory } from 'history'
export const history = createBrowserHistory()
在App.tsx
中加上<Router history={history}>
import React, { lazy, Suspense } from 'react'
import { DotLoading } from 'antd-mobile'
// App.tsx
// 导入路由
import { Router, Route, Redirect } from 'react-router-dom'
+ import { history } from '@/utils/history'
// 导入页面组件
const Login = lazy(() => import('./pages/Login/Login'))
const Layout = lazy(() => import('./pages/Layout/Layout'))
const Edit = lazy(() => import('./pages/Profile/Edit'))
const Chat = lazy(() => import('./pages/Profile/Chat'))
// 配置路由规则
function App () {
return (
+ <Router history={history}>
<Suspense fallback={ <span >
<div style={{ color: 'skyblue' }}>
<span>loading</span>
<DotLoading color='currentColor' />
</div>
</span> }>
<div className="app" >
<Route exact path="/" render={() => <Redirect to="/home" />} />
{/* <Route path="/home"><Layout /></Route> */}
<Route path="/home" component={Layout}></Route>
<Route path="/login"><Login /></Route>
<Route path="/profile/edit"><Edit /></Route>
<Route path="/chat"><Chat /></Route>
</div>
</Suspense>
+ </Router>
)
}
此时在组件中就能跳转啦
import { useHistory } from 'react-router-dom'
const history = useHistory()
history.push()