• [尚硅谷React笔记]——第9章 ReactRouter6


    目录:

    1. 课程说明
    2. 一级路由
    3. 重定向
    4. NavLink高亮
    5. useRoutes路由表
    6. 嵌套路由
    7. 路由的params参数
    8. 路由的search参数
    9. 路由的state参数
    10. 编程式路由导航
    11. useRouterContext
    12. useNavigationType
    13. useOutlet
    14. useResolvedPath()
    15. 总结
    16. 项目地址

    1.课程说明

    概述

    • React Router以三个不同的包发布到npm 上,它们分别为:
      • 1.react-router:路由的核心库,提供了很多的:组件、钩子。
      • 2.react-router-dom:包含react-router所有内容,并添加一些专门用于DOM的组件,例如等。
      • 3. react-router-native:包括react-router所有内容,并添加一些专门用于ReactNative的API例如:等。
    • 2.与React Router 5.x版本相比,改变了什么?
      • 1.内置组件的变化:移除,新增等。
      • ⒉.语法的变化: component={About]变为element={}等。
      • 3.新增多个hook: useParams 、useNavigate 、useMatch 等。
      • 4.官方明确推荐函数式组件了!!!

    2.一级路由 

    About.jsx

    1. import React from 'react';
    2. function About(props) {
    3. return (
    4. 我是About的内容

  • );
  • }
  • export default About;
  • Home.jsx

    1. import React from 'react';
    2. function Home(props) {
    3. return (
    4. 我是Home的内容

  • );
  • }
  • export default Home;
  •  App.js

    1. import React from 'react';
    2. import {NavLink, Routes, Route} from "react-router-dom";
    3. import About from "./pages/About";
    4. import Home from "./pages/Home";
    5. function App(props) {
    6. return (
    7. "row">
    8. "col-xs-offset-2 col-xs-8">
    9. "page-header">

      React Router Demo

  • "row">
  • "col-xs-2 col-xs-offset-2">
  • "list-group">
  • "list-group-item" to="/about">About
  • "list-group-item" to="/home">Home
  • "col-xs-6">
  • "panel">
  • "panel-body">
  • "/about" element={}>
  • "/home" element={}>
  • );
  • }
  • export default App;
  • index.js

    1. import React from 'react';
    2. import ReactDOM from 'react-dom/client';
    3. import App from './App';
    4. import {BrowserRouter} from "react-router-dom";
    5. const root = ReactDOM.createRoot(document.getElementById('root'));
    6. root.render(
    7. );

    3.重定向

    App.js

    1. import React from 'react';
    2. import {NavLink, Routes, Route, Navigate} from "react-router-dom";
    3. import About from "./pages/About";
    4. import Home from "./pages/Home";
    5. function App(props) {
    6. return (
    7. "row">
    8. "col-xs-offset-2 col-xs-8">
    9. "page-header">

      React Router Demo

    10. "row">
    11. "col-xs-2 col-xs-offset-2">
    12. "list-group">
    13. "list-group-item" to="/about">About
    14. "list-group-item" to="/home">Home
    15. "col-xs-6">
    16. "panel">
    17. "panel-body">
    18. "/ABOUT" caseSensitive element={}>
    19. "/home" element={}>
    20. "/" element={"/about"/>}>
    21. );
    22. }
    23. export default App;

     Home.jsx

    1. import React, {useState} from 'react';
    2. import {Navigate} from "react-router-dom";
    3. function Home(props) {
    4. const [sum, setSum] = useState(1)
    5. return (
    6. 我是Home的内容

    7. {sum === 2 ? "/about/" replace={true}/> :

      当前sum的值是:{sum}

      }
    8. );
    9. }
    10. export default Home;

    4.NavLink高亮

    App.js

    1. import React from 'react';
    2. import {NavLink, Routes, Route, Navigate} from "react-router-dom";
    3. import About from "./pages/About";
    4. import Home from "./pages/Home";
    5. function App(props) {
    6. function computedClassName({isActive}) {
    7. return isActive ? 'list-group-item atguigu' : 'list-group-item'
    8. }
    9. return (
    10. "row">
    11. "col-xs-offset-2 col-xs-8">
    12. "page-header">

      React Router Demo

    13. "row">
    14. "col-xs-2 col-xs-offset-2">
    15. "list-group">
    16. "/about">About
    17. "/home">Home
    18. "col-xs-6">
    19. "panel">
    20. "panel-body">
    21. "/about" element={}>
    22. "/home" element={}>
    23. "/" element={"/about"/>}>
    24. );
    25. }
    26. export default App;

     About.jsx

    1. import React from 'react';
    2. function About(props) {
    3. return (
    4. 我是About的内容

    5. );
    6. }
    7. export default About;

    Home.jsx

    1. import React from 'react';
    2. function Home(props) {
    3. return (
    4. 我是Home的内容

    5. );
    6. }
    7. export default Home;

    5.useRoutes路由表

    route/index.js

    1. import About from "../pages/About";
    2. import Home from "../pages/Home";
    3. import {Navigate} from "react-router-dom";
    4. export default [
    5. {
    6. path: '/about',
    7. element:
    8. },
    9. {
    10. path: '/home',
    11. element:
    12. },
    13. {
    14. path: '/',
    15. element: "/about">
    16. },
    17. ]

     App.js

    1. import React from 'react';
    2. import {NavLink, useRoutes} from "react-router-dom";
    3. import routes from "./routes";
    4. function App(props) {
    5. const element = useRoutes(routes)
    6. return (
    7. "row">
    8. "col-xs-offset-2 col-xs-8">
    9. "page-header">

      React Router Demo

    10. "row">
    11. "col-xs-2 col-xs-offset-2">
    12. "list-group">
    13. "list-group-item" to="/about">About
    14. "list-group-item" to="/home">Home
    15. "col-xs-6">
    16. "panel">
    17. "panel-body">
    18. {/**/}
    19. {/* "/about" element={}>*/}
    20. {/* "/home" element={}>*/}
    21. {/* "/" element={"/about"/>}>*/}
    22. {/**/}
    23. {element}
    24. );
    25. }
    26. export default App;

     6.嵌套路由

     App.js

    1. import React from 'react';
    2. import {NavLink, useRoutes} from "react-router-dom";
    3. import routes from "./routes";
    4. function App(props) {
    5. const element = useRoutes(routes)
    6. return (
    7. "row">
    8. "col-xs-offset-2 col-xs-8">
    9. "page-header">

      React Router Demo

    10. "row">
    11. "col-xs-2 col-xs-offset-2">
    12. "list-group">
    13. "list-group-item" to="/about">About
    14. "list-group-item" end to="/home">Home
    15. "col-xs-6">
    16. "panel">
    17. "panel-body">
    18. {/**/}
    19. {/* "/about" element={}>*/}
    20. {/* "/home" element={}>*/}
    21. {/* "/" element={"/about"/>}>*/}
    22. {/**/}
    23. {element}
    24. );
    25. }
    26. export default App;

    route/index.js

    1. import About from "../pages/About";
    2. import Home from "../pages/Home";
    3. import {Navigate} from "react-router-dom";
    4. import News from "../pages/News";
    5. import Message from "../pages/Message";
    6. export default [
    7. {
    8. path: '/about',
    9. element:
    10. },
    11. {
    12. path: '/home',
    13. element: ,
    14. children: [
    15. {
    16. path: 'news',
    17. element:
    18. },
    19. {
    20. path: 'message',
    21. element:
    22. }
    23. ]
    24. },
    25. {
    26. path: '/',
    27. element: "/about">
    28. },
    29. ]

    News.jsx

    1. import React from 'react';
    2. function News(props) {
    3. return (
      • news001
      • news002
      • news003
      • );
      • }
      • export default News;

      Message.jsx

      1. import React from 'react';
      2. function Message(props) {
      3. return (
        • );
        • }
        • export default Message;

        Home.jsx

        1. import React from 'react';
        2. import {NavLink, Outlet} from "react-router-dom";
        3. function Home(props) {
        4. return (
        5. Home组件内容

          • "nav nav-tabs">
        6. "list-group-item" to="news">News
        7. {/*"list-group-item" to="./news">News*/}
        8. {/*"list-group-item" to="/home/news">News*/}
        9. "list-group-item " to="message">Message
        10. {/*"list-group-item " to="./message">Message*/}
        11. {/*"list-group-item " to="/home/message">Message*/}
        12. );
        13. }
        14. export default Home;

        About.jsx

        1. import React from 'react';
        2. function About(props) {
        3. return (
        4. 我是About的内容

        5. );
        6. }
        7. export default About;

        7.路由的params参数

        Detail.jsx

        1. import React from 'react';
        2. import {useMatch, useParams} from "react-router-dom";
        3. function Detail(props) {
        4. const {id, title, content} = useParams()
        5. const x = useMatch('/home/message/detail/:id/:title/:content')
        6. console.log(x)
        7. return (
          • 消息编号:{id}
          • 消息标题:{title}
          • 消息内容:{content}
          • );
          • }
          • export default Detail;

          Message.jsx

          1. import React, {useState} from 'react';
          2. import {Link, Outlet} from "react-router-dom";
          3. function Message(props) {
          4. const [messages] = useState([
          5. {id: '001', title: '消息1', content: '锄禾日当午'},
          6. {id: '002', title: '消息2', content: '汗滴禾下土'},
          7. {id: '003', title: '消息3', content: '谁知盘中餐'},
          8. {id: '004', title: '消息4', content: '粒粒皆辛苦'},
          9. ])
          10. return (
            • {
            • messages.map((m) => {
            • return (
            • ${m.id}/${m.title}/${m.content}`}>{m.title}  
            • )
            • })
            • }

            • );
            • }
            • export default Message;

            routes/index.js

            1. import About from "../pages/About";
            2. import Home from "../pages/Home";
            3. import {Navigate} from "react-router-dom";
            4. import News from "../pages/News";
            5. import Message from "../pages/Message";
            6. import Detail from "../pages/Detail";
            7. export default [
            8. {
            9. path: '/about',
            10. element:
            11. },
            12. {
            13. path: '/home',
            14. element: ,
            15. children: [
            16. {
            17. path: 'news',
            18. element:
            19. },
            20. {
            21. path: 'message',
            22. element: ,
            23. children: [
            24. {
            25. path: 'detail/:id/:title/:content',
            26. element:
            27. }
            28. ]
            29. }
            30. ]
            31. },
            32. {
            33. path: '/',
            34. element: "/about">
            35. },
            36. ]

            8.路由的search参数

            Detail.jsx

            1. import React from 'react';
            2. import {useLocation, useSearchParams} from "react-router-dom";
            3. function Detail(props) {
            4. const [search, setSearch] = useSearchParams()
            5. const id = search.get('id')
            6. const title = search.get('title')
            7. const content = search.get('content')
            8. const x = useLocation()
            9. console.log(x)
            10. return (
              • 消息编号:{id}
              • 消息标题:{title}
              • 消息内容:{content}
              • );
              • }
              • export default Detail;

              Message.jsx

              1. import React, {useState} from 'react';
              2. import {Link, Outlet} from "react-router-dom";
              3. function Message(props) {
              4. const [messages] = useState([
              5. {id: '001', title: '消息1', content: '锄禾日当午'},
              6. {id: '002', title: '消息2', content: '汗滴禾下土'},
              7. {id: '003', title: '消息3', content: '谁知盘中餐'},
              8. {id: '004', title: '消息4', content: '粒粒皆辛苦'},
              9. ])
              10. return (
                • {
                • messages.map((m) => {
                • return (
                • {/*${m.id}/${m.title}/${m.content}`}>{m.title}  */}
                • ${m.id}&title=${m.title}&content=${m.content}`}>{m.title}
                •   
                • )
                • })
                • }

                • );
                • }
                • export default Message;

                index.js

                1. import About from "../pages/About";
                2. import Home from "../pages/Home";
                3. import {Navigate} from "react-router-dom";
                4. import News from "../pages/News";
                5. import Message from "../pages/Message";
                6. import Detail from "../pages/Detail";
                7. export default [
                8. {
                9. path: '/about',
                10. element:
                11. },
                12. {
                13. path: '/home',
                14. element: ,
                15. children: [
                16. {
                17. path: 'news',
                18. element:
                19. },
                20. {
                21. path: 'message',
                22. element: ,
                23. children: [
                24. {
                25. path: 'detail',
                26. element:
                27. }
                28. ]
                29. }
                30. ]
                31. },
                32. {
                33. path: '/',
                34. element: "/about">
                35. },
                36. ]

                9.路由的state参数

                Detail.jsx

                1. import React from 'react';
                2. import {useLocation} from "react-router-dom";
                3. function Detail(props) {
                4. const {state: {id, title, content}} = useLocation()
                5. return (
                  • 消息编号:{id}
                  • 消息标题:{title}
                  • 消息内容:{content}
                  • );
                  • }
                  • export default Detail;

                  Message.jsx

                  1. import React, {useState} from 'react';
                  2. import {Link, Outlet} from "react-router-dom";
                  3. function Message(props) {
                  4. const [messages] = useState([
                  5. {id: '001', title: '消息1', content: '锄禾日当午'},
                  6. {id: '002', title: '消息2', content: '汗滴禾下土'},
                  7. {id: '003', title: '消息3', content: '谁知盘中餐'},
                  8. {id: '004', title: '消息4', content: '粒粒皆辛苦'},
                  9. ])
                  10. return (
                    • {
                    • messages.map((m) => {
                    • return (
                    • {/*${m.id}/${m.title}/${m.content}`}>{m.title}  */}
                    • {/*${m.id}&title=${m.title}&content=${m.content}`}>{m.title}*/}
                    • state={{id: m.id, title: m.title, content: m.content}}>{m.title}
                    •   
                    • )
                    • })
                    • }

                    • );
                    • }
                    • export default Message;

                    routes/index.js

                    1. import About from "../pages/About";
                    2. import Home from "../pages/Home";
                    3. import {Navigate} from "react-router-dom";
                    4. import News from "../pages/News";
                    5. import Message from "../pages/Message";
                    6. import Detail from "../pages/Detail";
                    7. export default [
                    8. {
                    9. path: '/about',
                    10. element:
                    11. },
                    12. {
                    13. path: '/home',
                    14. element: ,
                    15. children: [
                    16. {
                    17. path: 'news',
                    18. element:
                    19. },
                    20. {
                    21. path: 'message',
                    22. element: ,
                    23. children: [
                    24. {
                    25. path: 'detail',
                    26. element:
                    27. }
                    28. ]
                    29. }
                    30. ]
                    31. },
                    32. {
                    33. path: '/',
                    34. element: "/about">
                    35. },
                    36. ]

                    10.编程式路由导航

                    Header.jsx

                    1. import React from 'react';
                    2. import {useNavigate} from "react-router-dom";
                    3. function Header(props) {
                    4. const navigate = useNavigate()
                    5. function back() {
                    6. navigate(-1)
                    7. }
                    8. function forward() {
                    9. navigate(1)
                    10. }
                    11. return (
                    12. "col-xs-offset-2 col-xs-8">
                    13. "page-header">
                    14. React Router Demo

                    15. );
                    16. }
                    17. export default Header;

                    Message.jsx

                    1. import React, {useState} from 'react';
                    2. import {Link, Outlet, useNavigate} from "react-router-dom";
                    3. function Message(props) {
                    4. const [messages] = useState([
                    5. {id: '001', title: '消息1', content: '锄禾日当午'},
                    6. {id: '002', title: '消息2', content: '汗滴禾下土'},
                    7. {id: '003', title: '消息3', content: '谁知盘中餐'},
                    8. {id: '004', title: '消息4', content: '粒粒皆辛苦'},
                    9. ])
                    10. const navigate = useNavigate()
                    11. function showDetail(m) {
                    12. navigate('detail', {replace: false, state: {id: m.id, title: m.title, content: m.content}})
                    13. }
                    14. return (
                      • {
                      • messages.map((m) => {
                      • return (
                      • {/*${m.id}/${m.title}/${m.content}`}>{m.title}  */}
                      • {/*${m.id}&title=${m.title}&content=${m.content}`}>{m.title}*/}
                      • state={{id: m.id, title: m.title, content: m.content}}>{m.title}
                      • )
                      • })
                      • }

                      • );
                      • }
                      • export default Message;

                      App.js

                      1. import React from 'react';
                      2. import {NavLink, useRoutes} from "react-router-dom";
                      3. import routes from "./routes";
                      4. import Header from "./components/Header";
                      5. function App(props) {
                      6. const element = useRoutes(routes)
                      7. return (
                      8. "row">
                      9. "row">
                      10. "col-xs-2 col-xs-offset-2">
                      11. "list-group">
                      12. "list-group-item" to="/about">About
                      13. "list-group-item" to="/home">Home
                      14. "col-xs-6">
                      15. "panel">
                      16. "panel-body">
                      17. {/**/}
                      18. {/* "/about" element={}>*/}
                      19. {/* "/home" element={}>*/}
                      20. {/* "/" element={"/about"/>}>*/}
                      21. {/**/}
                      22. {element}
                      23. );
                      24. }
                      25. export default App;

                      11.useRouterContext

                      index.js

                      1. import React from 'react';
                      2. import ReactDOM from 'react-dom/client';
                      3. import App from './App';
                      4. import {BrowserRouter} from "react-router-dom";
                      5. import Demo from "./components/Demo";
                      6. const root = ReactDOM.createRoot(document.getElementById('root'));
                      7. root.render(
                      8. ,
                      9. );

                       App.js

                      1. import React from 'react';
                      2. import {NavLink, useInRouterContext, useRoutes} from "react-router-dom";
                      3. import routes from "./routes";
                      4. import Header from "./components/Header";
                      5. function App(props) {
                      6. const element = useRoutes(routes)
                      7. console.log('@',useInRouterContext())
                      8. return (
                      9. "row">
                      10. "row">
                      11. "col-xs-2 col-xs-offset-2">
                      12. "list-group">
                      13. "list-group-item" to="/about">About
                      14. "list-group-item" to="/home">Home
                      15. "col-xs-6">
                      16. "panel">
                      17. "panel-body">
                      18. {/**/}
                      19. {/* "/about" element={}>*/}
                      20. {/* "/home" element={}>*/}
                      21. {/* "/" element={"/about"/>}>*/}
                      22. {/**/}
                      23. {element}
                      24. );
                      25. }
                      26. export default App;

                      Demo.jsx

                      1. import React from 'react';
                      2. import {useInRouterContext} from "react-router-dom";
                      3. function Demo(props) {
                      4. console.log(useInRouterContext())
                      5. return (
                      6. demo
                      7. );
                      8. }
                      9. export default Demo;

                       Header.jsx

                      1. import React from 'react';
                      2. import {useInRouterContext, useNavigate} from "react-router-dom";
                      3. function Header(props) {
                      4. const navigate = useNavigate()
                      5. console.log(useInRouterContext())
                      6. function back() {
                      7. navigate(-1)
                      8. }
                      9. function forward() {
                      10. navigate(1)
                      11. }
                      12. return (
                      13. "col-xs-offset-2 col-xs-8">
                      14. "page-header">
                      15. React Router Demo

                      16. );
                      17. }
                      18. export default Header;

                      12.useNavigationType

                       News.jsx

                      1. import React from 'react';
                      2. import {useNavigationType} from "react-router-dom";
                      3. function News(props) {
                      4. console.log(useNavigationType())
                      5. return (
                        • news001
                        • news002
                        • news003
                        • );
                        • }
                        • export default News;

                         

                        13.useOutlet

                        1. const result = useoutlet( )
                        2. console.log( result)
                        3. //如果嵌套路由没有挂载,则result为null
                        4. //如果嵌套路由已经挂载,则展示嵌套的路由对象

                        Home.jsx

                        1. import React from 'react';
                        2. import {NavLink, Outlet, useOutlet} from "react-router-dom";
                        3. function Home(props) {
                        4. console.log(useOutlet())
                        5. return (
                        6. Home组件内容

                          • "nav nav-tabs">
                        7. "list-group-item" to="news">News
                        8. "list-group-item " to="message">Message
                        9. );
                        10. }
                        11. export default Home;

                         

                        14.useResolvedPath()

                        News.jsx

                        1. import React from 'react';
                        2. import {useResolvedPath} from "react-router-dom";
                        3. function News(props) {
                        4. console.log(useResolvedPath('/user?id=001&name=tom#qwe'))
                        5. return (
                          • news001
                          • news002
                          • news003
                          • );
                          • }
                          • export default News;

                          15.总结:

                          2.Component

                          1. 

                          2.

                          3.

                          1. v6版本中移出了先前的,引入了新的替代者:
                          2. 要配合使用,且必须要用包裹
                          3. 相当于一个if语句,如果其路径与当前URL匹配,则呈现其对应的组件。 
                          4. 属性用于指定:匹配时是否区分大小写(默认为false)。
                          5. 当URL发生变化时,都会查看其所有子元素以找到最佳匹配并呈现组件。
                          6. 组件来渲染其子路由。
                          7. 示例代码:

                          4.

                          5.

                           

                          6.<Navigate>

                           

                          7.

                          3.Hooks

                          1.useRoutes()

                          2.useNavigate

                           

                          3. useParams()

                           

                          4.useSearchParams() 

                           

                          5.useLocation()

                           

                          6.useMatch() 

                           

                          16.项目地址

                           https://gitee.com/coderPatrickStar/react/tree/master/20231003

                        6. 相关阅读:
                          【毕业设计】 基于单片机的移动共享充电宝设计与实现 - 物联网嵌入式 stm32 c51
                          891. 子序列宽度之和 : 逐步分析如何求解对展开式的最终贡献
                          软件供应链攻击的新形式
                          redis宕机导致数据丢失的重大生产事故总结
                          R可视乎|灯芯柱状图代码解读
                          封装unordered_map和unordered_set
                          2023高频前端面试题-http
                          用于静电放电敏感器件的包装的性能和要求分类-2
                          C#操作MySQL从入门到精通(18)——使用组合查询
                          2022蓝帽杯初赛电子取证
                        7. 原文地址:https://blog.csdn.net/qq_56444564/article/details/134214303