一 升級(jí)對(duì)應(yīng)版本
- 升級(jí)到 React v16.8 或更高版本
- 升級(jí)到 React Router v5.1
- 升級(jí)到 React Router v6
具體使用參考官網(wǎng)
2. <Switch>元素升級(jí)為<Routes>
在v6中,component屬性被替換成了element,并且需要傳入組件
//V5版本
import {BrowserRouter, Route, Switch} from 'react-router-dom';
<BrowserRouter>
<Switch>
<Route path="/" > <Home /></Route>
</Switch>
</BrowserRouter>
//V6版本
import {BrowserRouter, Route, Routes} from 'react-router-dom';
<BrowserRouter>
<Routes>
<Route path="/" exact element={<Home/>} />
</Routes>
</BrowserRouter>
二 <Redirect>改為<Navigate>
//V5版本
import { Redirect } from 'react-router-dom';
//重定向到首頁(yè)
return <Redirect to="/home" />
//V6版本
import { Navigate } from 'react-router-dom';
//重定向到首頁(yè)
return <Navigate to="/home" />
三 useNavigate替代useHistory使用
//V5版本
import { useHistory } from "react-router-dom";
const history = useHistory();
history.push("/home"); // 跳轉(zhuǎn)路由
history.go();
history.goback();
history.location;
history.replace();
//V6版本
import {useNavigate} from 'react-router-dom';
const navigate = useNavigate();
navigate("/home"); // 跳轉(zhuǎn)路由
navigate('/home', {replace: true});
navigate(-1); //后退
navigate(1); //前進(jìn)
四 V6路由嵌套
// 路由使用
<Routes>
<Route path='/home/*' element={<Home />}
<Route path='home-page' element={<div>我是嵌套內(nèi)容</div>} />
<Route/>
</Routes>
// 組件中使用
import {Outlet} from 'react-router-dom';
const Home = () => {
return(
<div>
<h1>home</h1>
<Outlet />
</div>
)
}
export default Home;
五 V6 useRoutes代替react-router-config
export const routes = [
{
path: '/',
element: <Layout />,
children: [
{
path: 'home',
meta: {
title: '首頁(yè)',
icon: ‘’,
},
children: [
{
path: 'homepage1',
element: <Homepage />,
meta: {
title: 'homepage1',
}
}
]
}
]
},
{
path: '/login',
element: <Login />,
meta: {
title: '登錄',
hideMenu: true
}
},
{
path: '*',
element: <Page404 />,
meta: {
title: '404',
hideMenu: true
}
},
];
const Routes = () => (
useRoutes(routes)
)
export default Routes;