react-router-dom V6版本使用

一 升級(jí)對(duì)應(yīng)版本

  1. 升級(jí)到 React v16.8 或更高版本
  2. 升級(jí)到 React Router v5.1
  3. 升級(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;
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容