react-router-dom v6 版本使用內(nèi)容詳解

1.路由組件

(1-1) v6 方式一 react-router-dom 常規(guī)
(1-2) v6 方式二 react-router-dom 使用 useRoutes

2.頁面跳轉(zhuǎn)

(2-1) Link 組件跳轉(zhuǎn)
(2-2) useNavigate hooks跳轉(zhuǎn),代替useHistory

3.獲取路由的參數(shù)

(3-1) useParams 獲取動態(tài)路由的值
(3-2) useSearchParams 獲取查詢字符串的值
(3-3) useLocation 獲取上一個頁面?zhèn)鬟f進(jìn)來的 state 參數(shù) v5、v6一樣

介紹:

v6 較 v5版本,在常用的路由組件管理、頁面跳轉(zhuǎn)、頁面跳轉(zhuǎn)帶參等功能使用,需要注意。

官網(wǎng):https://reactrouter.com/docs/en/v6

安裝:

//自己選一個,幾種方式都可以
npm方式:
    npm install --save react-router-dom

cnpm方式:
    cnpm install --save react-router-dom

yarn方式:
    yarn add react-router-dom
    
指定版本:使用@
    yarn add react-router-dom@5.2.1

見:package.json文件內(nèi)dependencies新增了react-router-dom的版本號,即安裝成功
重啟下項(xiàng)目(不需要install)

1.路由組件
BrowserRouter:引用不變
Routes:替換 v5 的 Switch 組件
Route:引用不變。參數(shù) element 替換 v5 的 component、render 組件

(1-1) 創(chuàng)建 src/routers/index.js

import Home from '../views/Home';
import About from '../views/About'
import Err404 from '../views/Err404'
const routers = [
  {
    title: '首頁',
    path: '/',
    component: Home,
  },
  {
    title: '關(guān)于',
    path: '/inbox',
    component: About,
  },
  {
    title: '404',
    path: '/inbox',
    component: Err404,
  }
];

export default routers;

(1-2) 調(diào)用

v6 方式一 react-router-dom 常規(guī)(推薦 - 可以設(shè)置title更方便)

// v6 方式一
import React from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import routers from './routers';

const App = () => {
  return (
    <Router>
      <Routes> // 不是老版本的:Switch
        {routers.map((item, index) => {
          return (
            <Route
              key={index}
              exact
              path={item.path}
              element={<item.component />} // 不是老版本的:component 或 render
              // onEnter、onBeforeMount、onMounted事件,會在組件初始化時執(zhí)行一次,切換路由不執(zhí)行
              // 若 修改 document.title 查看文檔:https://blog.csdn.net/weixin_44461275/article/details/122843160
            />
          );
        })}
      </Routes>
    </Router>
  );
};

export default App;


//v5
import React from 'react';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import routers from './routers';

const App = () => {
  return (
    <Router>
      <Switch>
        {routers.map((item, index) => {
          return (
            <Route
              key={index}
              exact
              path={item.path}
              render={() => { // 推薦使用 render 不用 component
                document.title = item.title;
                return <item.component />;
              }}
              //或:
              //component={<item.component />}
            />
          );
        })}
      </Switch>
    </Router>
  );
};

export default App;

v6 方式二 react-router-dom + 使用 useRoutes

//路由json組件
import Layout from '../layout'
import About from '../views/About'
import Home from '../views/Home'
import AboutIndex from '../views/About/Component/AboutIndex'
import AboutList from '../views/About/Component/AboutList'
import Error404 from '../views/Error404'

const routes = [
    {
        path: "/",
        element: <Layout />, 
        children: [
            {
                index : true,
                element: <Home />
            },
            {
                path: "/about",
                element: <About />,
                children: [
                    { index : true, element: <AboutIndex />},
                    { path : "/about/:id", element :<AboutList />}
                ]
            },
        ]
    },
    {
       path: "*",
       element: <Error404 />,
    }
]

export default routes

//app.js
import React from 'react';
import { BrowserRouter as Router, useRoutes } from 'react-router-dom';
import routers from '../routers';

function App() {
  const GetRoutes = () => useRoutes(routers); //一定要是函數(shù)內(nèi)
  
  return (
    <Router>
      <GetRoutes />
    </Router>
  );
}

export default App;

2.頁面跳轉(zhuǎn)
(2-1) Link 組件跳轉(zhuǎn)

import React from "react";
import { Link } from "react-router-dom";

function DEMO() {
  return (
    <Link to="/aaa">點(diǎn)擊跳轉(zhuǎn)頁面</Link>
  );
}

export default DEMO;

(2-2) useNavigate hooks跳轉(zhuǎn),代替useHistory

import React from "react";
import { useNavigate } from "react-router-dom";

function DEMO() {
    const navigate = useNavigate();

    // 點(diǎn)擊跳轉(zhuǎn)頁面
    function hrefAaa() {
        navigate('/aaa')
    }

    // history replace模式
    function hrefReplace() {
        navigate("/aaa", { replace: true });
    }

    // history.go(-1)
    function historyBack() {
        navigate(-1);
    }
    
    // 跳轉(zhuǎn)帶參數(shù)
    function hrefState() {
      navigate("/test", {
        state: { test: 111 },
      });
    }
    
    return (
        <>
            <div onClick={hrefAaa}>點(diǎn)擊跳轉(zhuǎn)頁面</div>
            <div onClick={hrefReplace}>history replace模式</div>
            <div onClick={historyBack}>返回上一個頁面</div>
        </>
    );
}

export default DEMO;

3.獲取路由的參數(shù)
useParams 獲取動態(tài)路由的值
useSearchParams 獲取查詢字符串的值
useLocation 獲取上一個頁面?zhèn)鬟f進(jìn)來的 state 參數(shù) v5、v6一樣

import React,{ useEffect } from "react";
import { useParams, useSearchParams, useLocation } from "react-router-dom";

export default function GoodsDetail() {
  const params = useParams(); // 獲取動態(tài)路由的值
  const [searchParams, setSearchParams] = useSearchParams(); // 獲取查詢字符串的值
  const location = useLocation(); // 獲取上一個頁面?zhèn)鬟f進(jìn)來的 state 參數(shù)
  
  useEffect(() => {
    // 一個對象,key 為動態(tài)字符串的 key
    console.log(params); // {id: '123'}

    console.log(location.state); // { test: 111 }  上一個頁面帶參獲取 非url上面的search

    // 輸入 http://localhost:3000/goods/123?name=1111
    console.log(searchParams.get("name")); // 111
  }, []);

  const handleSetSearch = () => {
    // 新增-修改
    setSearchParams({
      keyName: 2222
    }); // /aaa?keyName=2222
  };
  
  return (
    <div onClick={handleSetSearch}>Page</div>
  );
}

來自:https://blog.csdn.net/weixin_44461275/article/details/122968904

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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

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