1. 概述

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

      2. component

      2.1

      BrowserRouter和HashRouter
      1. import React from 'react'
      2. import { ReactDOM } from 'react-dom'
      3. import { BrowserRouter} from 'react-router-dom'
      4. import App from './App'
      5. ReactDOM.render(
      6. <BrowserRouter>
      7. <App/>
      8. </BrowserRouter>,
      9. document.getElementById('root')
      10. )

      2.2

      2.3

      之前使用Switch包含, 为了提高效率。只要有匹配到的路由, 就不会继续执行, 且Switch可加可不加。
      但是Rourtes是必须要加的。匹配规则和Switch一样。

image.png

  1. import React, { Component} from 'react';
  2. import './components/style.css'
  3. import {NavLink, Routes, Route} from 'react-router-dom'
  4. import Home from './components/Home'
  5. import About from './components/About'
  6. class App extends Component {
  7. render() {
  8. return (
  9. <div className='parent'>
  10. <h2>我是APP组件</h2>
  11. {/* 路由连接 */}
  12. <NavLink to='/about'>About</NavLink>&nbsp;&nbsp;&nbsp;
  13. <NavLink to='/home'>Home</NavLink>
  14. <hr/>
  15. {/* 注册路由 */}
  16. <Routes>
  17. <Route path = '/about' element={<About/>}></Route>
  18. <Route path = '/home' element={<Home/>}></Route>
  19. </Routes>
  20. </div>
  21. );
  22. }
  23. }
  24. export default App;

image.png

2.4

2.5

  1. import React from 'react'
  2. import './components/style.css'
  3. import { NavLink, Routes, Route, Navigate } from 'react-router-dom'
  4. import Home from './components/Home'
  5. import About from './components/About'
  6. export default function App() {
  7. function getClassName({isActive}) {
  8. return isActive ? 'activeLink' : ''
  9. }
  10. return (
  11. <div className="parent">
  12. <h2>我是APP组件</h2>
  13. {/* 路由连接 */}
  14. <NavLink to="/about" className={getClassName}>
  15. About
  16. </NavLink>
  17. &nbsp;&nbsp;&nbsp;
  18. <NavLink to="/home" className={getClassName} >
  19. Home
  20. </NavLink>
  21. <hr />
  22. {/* 注册路由 */}
  23. <Routes>
  24. <Route path="/about" element={<About />}></Route>
  25. <Route path="/home" element={<Home />}></Route>
  26. <Route path="/" element={<Navigate to="/home" />} />
  27. </Routes>
  28. </div>
  29. )
  30. }

2.6

一渲染,视图就会切换。

  1. <Routepath='/'element={<Navigateto="/home"/>}/>
  2. import React, { Component} from 'react';
  3. import './components/style.css'
  4. import {NavLink, Routes, Route, Navigate} from 'react-router-dom'
  5. import Home from './components/Home'
  6. import About from './components/About'
  7. class App extends Component {
  8. render() {
  9. return (
  10. <div className='parent'>
  11. <h2>我是APP组件</h2>
  12. {/* 路由连接 */}
  13. <NavLink to='/about'>About</NavLink>&nbsp;&nbsp;&nbsp;
  14. <NavLink to='/home'>Home</NavLink>
  15. <hr/>
  16. {/* 注册路由 */}
  17. <Routes>
  18. <Route path = '/about' element={<About/>}></Route>
  19. <Route path = '/home' element={<Home/>}></Route>
  20. <Route path='/' element={<Navigate to="/home"/>}/>
  21. </Routes>
  22. </div>
  23. );
  24. }
  25. }
  26. export default App;
  1. import React, { useState} from 'react'
  2. import { Navigate} from'react-router-dom'
  3. export default function Home() {
  4. const [count, setCount] = useState(0)
  5. return (
  6. <div>
  7. <h2>我是Home组件</h2>
  8. {
  9. count === 2? <Navigate to='/about'/>:<h3>count当前的值为:{count}</h3>
  10. }
  11. <button onClick={() => setCount(2)}>加</button>
  12. </div>
  13. )
  14. }

2.7

3. hooks

3.1 useRoutes

  1. import React from 'react'
  2. import './components/style.css'
  3. import { NavLink,Navigate, useRoutes } from 'react-router-dom'
  4. import Home from './components/Home'
  5. import About from './components/About'
  6. export default function App() {
  7. const element = useRoutes([
  8. {
  9. path:'/home',
  10. element:<Home />
  11. },
  12. {
  13. path:'/about',
  14. element:<About />
  15. },
  16. {
  17. path:'/',
  18. element:<Navigate to='/home' />
  19. }
  20. ])
  21. function getClassName({isActive}) {
  22. return isActive ? 'activeLink' : ''
  23. }
  24. return (
  25. <div className="parent">
  26. <h2>我是APP组件</h2>
  27. {/* 路由连接 */}
  28. <NavLink to="/about" className={getClassName}>
  29. About
  30. </NavLink>
  31. &nbsp;&nbsp;&nbsp;
  32. <NavLink to="/home" className={getClassName} >
  33. Home
  34. </NavLink>
  35. <hr />
  36. {/* 注册路由 */}
  37. {element}
  38. </div>
  39. )
  40. }
  1. import Home from '../components/Home'
  2. import About from '../components/About'
  3. import { Navigate } from 'react-router-dom'
  4. const routes = [
  5. {
  6. path: '/home',
  7. element: <Home />,
  8. },
  9. {
  10. path: '/about',
  11. element: <About />,
  12. },
  13. {
  14. path: '/',
  15. element: <Navigate to="/home" />,
  16. },
  17. ]
  18. export default routes;
  1. import React from 'react'
  2. import './components/style.css'
  3. import { NavLink, useRoutes } from 'react-router-dom'
  4. import routes from './routes'
  5. export default function App() {
  6. // 根据路由表生成对应的路由规则
  7. const element = useRoutes(routes)
  8. function getClassName({isActive}) {
  9. return isActive ? 'activeLink' : ''
  10. }
  11. return (
  12. <div className="parent">
  13. <h2>我是APP组件</h2>
  14. {/* 路由连接 */}
  15. <NavLink to="/home" className={getClassName} >
  16. Home
  17. </NavLink>
  18. &nbsp;&nbsp;&nbsp;
  19. <NavLink to="/about" className={getClassName}>
  20. About
  21. </NavLink>
  22. <hr />
  23. {/* 注册路由 */}
  24. {element}
  25. </div>
  26. )
  27. }
  1. import React, { useState} from 'react'
  2. import { Navigate, NavLink, Outlet} from'react-router-dom'
  3. export default function Home() {
  4. const [count, setCount] = useState(0)
  5. function getClassName({isActive}) {
  6. return isActive ? 'activeLink' : ''
  7. }
  8. return (
  9. <div>
  10. <h2>我是Home组件</h2>
  11. {
  12. count === 2? <Navigate to='/about'/>:<h3>count当前的值为:{count}</h3>
  13. }
  14. <button onClick={() => setCount(2)}>加</button>
  15. <hr />
  16. <NavLink to='news' className={getClassName} >News</NavLink> &nbsp;&nbsp;&nbsp;
  17. <NavLink to='message' className={getClassName} >Message</NavLink>
  18. <Outlet />
  19. </div>
  20. )
  21. }
  1. //规则
  2. {
  3. path:'message',
  4. element:<Message/>,
  5. children:[
  6. {
  7. path:'detail/:id/:title/:content',
  8. element:<Detail/>
  9. }
  10. ]
  11. }
  12. //列表
  13. <ul>
  14. {message.map((item) => {
  15. return (
  16. <li key={item.id}>
  17. <Link to={`detail/${item.id}/${item.title}/${item.content}`}> {`id${item.id}`}</Link>
  18. </li>
  19. )
  20. })}
  21. </ul>
  22. //详情
  23. import React from 'react'
  24. import { useParams} from 'react-router-dom'
  25. export default function Detail() {
  26. const {id, title, content} = useParams()
  27. return (
  28. <div>
  29. <h2>Id:{id}</h2>
  30. <h2>title:{title}</h2>
  31. <h2>content:{content}</h2>
  32. </div>
  33. )
  34. }
  1. //规则
  2. {
  3. path:'message',
  4. element:<Message/>,
  5. children:[
  6. {
  7. path:'detail/:id/:title/:content',
  8. element:<Detail/>
  9. }
  10. ]
  11. }
  12. //列表
  13. <ul>
  14. {message.map((item) => {
  15. return (
  16. <li key={item.id}>
  17. <Link to={`detail/${item.id}/${item.title}/${item.content}`}> {`id${item.id}`}</Link>
  18. </li>
  19. )
  20. })}
  21. </ul>
  22. //详情
  23. import React from 'react'
  24. import { useMatch} from 'react-router-dom'
  25. export default function Detail() {
  26. const {params:{id,title,content}} = useMatch('/home/message/detail/:id/:title/:content')
  27. return (
  28. <div>
  29. <h2>Id:{id}</h2>
  30. <h2>title:{title}</h2>
  31. <h2>context:{content}</h2>
  32. </div>
  33. )
  34. }
  1. //规则表
  2. {
  3. path:'message',
  4. element:<Message/>,
  5. children:[
  6. {
  7. path:'detail',
  8. element:<Detail/>
  9. }
  10. ]
  11. }
  12. //列表
  13. <ul>
  14. {message.map((item) => {
  15. return (
  16. <li key={item.id}>
  17. <Link to={`detail?id=${item.id}&title=${item.title}&content=${item.content}`}> {`id${item.id}`}</Link>
  18. </li>
  19. )
  20. })}
  21. </ul>
  22. //详情
  23. import React from 'react'
  24. import { useSearchParams } from 'react-router-dom'
  25. export default function Detail() {
  26. const [search, setSearch] = useSearchParams()
  27. const id = search.get('id')
  28. const title = search.get('title')
  29. const content = search.get('content')
  30. return (
  31. <div>
  32. <button onClick={() =>setSearch('id=008&title=哈哈&content = 喜喜')}>点我修改收到的参数</button>
  33. <h2>Id:{id}</h2>
  34. <h2>title:{title}</h2>
  35. <h2>content:{content}</h2>
  36. </div>
  37. )
  38. }
  1. //规则
  2. {
  3. path:'message',
  4. element:<Message/>,
  5. children:[
  6. {
  7. path:'detail',
  8. element:<Detail/>
  9. }
  10. ]
  11. }
  12. //list
  13. <ul>
  14. {message.map((item) => {
  15. return (
  16. <li key={item.id}>
  17. <Link to='detail' state = {{
  18. id:item.id,
  19. title:item.title,
  20. content: item.content
  21. }}> {`id${item.id}`}</Link>
  22. </li>
  23. )
  24. })}
  25. </ul>
  26. //详情
  27. import React from 'react'
  28. import { useLocation} from 'react-router-dom'
  29. export default function Detail() {
  30. const {state:{id, title, content}} = useLocation()
  31. return (
  32. <div>
  33. <h2>Id:{id}</h2>
  34. <h2>title:{title}</h2>
  35. <h2>context:{content}</h2>
  36. </div>
  37. )
  38. }
  1. import React, { useState } from 'react'
  2. import { Link, Outlet, useNavigate } from 'react-router-dom'
  3. export default function Message() {
  4. const [message] = useState([
  5. { id: 1001, title: '我是1001', content: '我是1001的内容' },
  6. { id: 2002, title: '我是2002', content: '我是2002的内容' },
  7. { id: 3003, title: '我是3003', content: '我是3003的内容' },
  8. ])
  9. const navigate = useNavigate()
  10. function showDetail(item) {
  11. navigate('detail', {
  12. replace: false,
  13. state: {
  14. id: item.id,
  15. title: item.title,
  16. content: item.content,
  17. },
  18. })
  19. }
  20. function forword(){
  21. navigate(1)
  22. }
  23. function back(){
  24. navigate(-1)
  25. }
  26. return (
  27. <div>
  28. <h2>Message组件</h2>
  29. <button onClick={forword}>前进</button>
  30. <button onClick={back}>后退</button>
  31. <ul>
  32. {message.map((item) => {
  33. return (
  34. <li key={item.id}>
  35. <Link
  36. to="detail"
  37. state={{
  38. id: item.id,
  39. title: item.title,
  40. content: item.content,
  41. }}
  42. >
  43. {' '}
  44. {`id${item.id}`}
  45. </Link>
  46. <button onClick={() => showDetail(item)}>查看详情</button>
  47. </li>
  48. )
  49. })}
  50. </ul>
  51. <hr />
  52. {/* 指定路由组件的位置 */}
  53. <Outlet />
  54. </div>
  55. )
  56. }