Basic use of React-Route routing, programmatic navigation routing jumps, nested routing and centralized routing configuration

1. Basic use of routing

1.1 Project environment preparation

The code is as follows (example):

# 创建react项目
$ yarn create vite react-router --template react

# 安装所有依赖包
$ yarn

# 启动项目
$ yarn dev

# 安装react-router包
$ yarn add react-router-dom@6

1.2 Basic use

insert image description here

The code is as follows (example):

// 引入必要的内置组件
import {
    
     BrowserRouter, Routes, Route, Link } from 'react-router-dom'

// 准备俩个路由组件

const Home = () => <div>this is home</div>
const About = () => <div>this is about</div>

function App() {
    
    
  return (
    <div className="App">
      {
    
    /* 按照规则配置路由 */}
      <BrowserRouter>
       //Link to为声明式跳转
        <Link to="/">首页</Link>
        <Link to="/about">关于</Link>
        <Routes>
          <Route path="/" element={
    
    <Home />}></Route>
          <Route path="/about" element={
    
    <About />}></Route>
        </Routes>
      </BrowserRouter>
    </div>
  )
}

export default App

2. Routing jump

2.1 Programmatic Navigation

Concept: Routing page jumps through js programming, such as jumping from the home page to the about page.
Implementation steps:
1. Import a useNavigate hook function
2. Execute the useNavigate function to get the jump function
3. Execute the jump function in the event to complete the routing jump
For example, jump from the Home page to the About page: ('/about' path is correct Can)

// 导入useNavigate函数
import {
    
     useNavigate } from 'react-router-dom'
const Home = () => {
    
    
  // 执行函数
  const navigate = useNavigate()
  return (
    <div>
      Home
      <button onClick={
    
     ()=> navigate('/about') }> 跳转关于页 </button>//路由跳转,无参
    </div>
  )
}

export default Home

Note: If you do not want to add history when jumping, you can add an additional parameter replace to true

navigate('/about', {
    
     replace: true } )

2.2 Jump parameters

Two ways:
1) SearchParams pass parameters
When passing parameters in the route, add parameters

 navigate('/about?=1001&name=cp')

When routing parameters, use useSearchParams to get

let [params] = useSearchParams()
//params是一个对象
let id = params.get('id')
let name = params.get('name')

2) Params pass parameters
When passing parameters in the route, add parameters

navigate('/about/1001')

The routing path needs to be modified before passing parameters

<Route path="/about/:id" element={
    
    <About />}></Route>

When fetching parameters from routes, use useParams to get them directly

let [params] = useParams()
//params是一个对象
let id = params.id

3. Nested routing

insert image description here
1. First build two first-level routing
Layout.js

function Layout(){
    
    
   return (
     <div>
      layout
     </div>
  )
}

export default Layout

Login.js

function Login(){
    
    
   return (
     <div>
       login
     </div>
  )
}

export default Login

Introduced in App.js

import {
    
    BrowserRouter,Routes,route} from 'react-router-dom'
import Layout from './Layout'
import Login from './Login'

function App(){
    
    
  return (
    <BrowserRouter>
      <Routes>
         <Route path='/' element={
    
    <Layout />}></Route>
         <Route path='/login' element={
    
    <Login />}></Route>
      </Routes>
    </BrowserRouter>
  )
}

export default App
  1. Build two secondary routes
    Board.js
function Board(){
    
    
   return (
     <div>
       board
     </div>
  )
}

export default Board

Article.js

function Article(){
    
    
   return (
     <div>
       article
     </div>
  )
}

export default Article

Both the first-level and second-level routing files have been created. At this time, nesting needs to be completed in two steps:
1) Define nested routing declarations in App.js

<Routes>
  <Route path="/"  element={
    
    <Layout/>}>
    //定义二级路由嵌套
    <Route path="board" element={
    
     <Board/> } />
    <Route path="article" element={
    
     <Article/> } />
  </Route>
  <Route path='/login' element={
    
    <Login />}></Route>
</Routes>

2) Use the specified secondary route exit in the first-level route
in Layout.js

import {
    
    Outlet} from 'react-router-dom'
function Layout(){
    
    
   return (
     <div>
      layout
      {
    
     /* 二级路由的path等于 一级path + 二级path  */ }
      <Link to="/board">board</Link>
      <Link to="/article">article</Link>
      //二级路由出口,也就是在Layout后
      <Outlet />
     </div>
  )
}

export default Layout

If you need to set the default route display of the page, you only need to remove the path of this route in App.js and replace it with index (home page). In the first-level routing, the corresponding second-level routing path can be set to empty.
in App.js

<Routes>
  <Route path="/"  element={
    
    <Layout/>}>
    <Route index element={
    
     <Board/> } />
    <Route path="article" element={
    
     <Article/> } />
  </Route>
</Routes>

in Layout.js

import {
    
     Outlet } from 'react-router-dom'

const Layout = () => {
    
    
  return (
    <div>
      layout
      {
    
     /* 默认二级不再具有自己的路径  */ }
      <Link to="/">board</Link>
      <Link to="/article">article</Link>
      {
    
     /* 二级路由出口 */ }
      <Outlet/>
    </div>
  )
}

4. 404 routing configuration

1. Prepare a NotFound component

const NotFound = () => {
    
    
  return <div>this Page is NotFound</div>
}

export default NotFound

in App.js

<BrowserRouter>
  <Routes>
    <Route path="/" element={
    
    <Layout />}>
      <Route index element={
    
    <Board />} />
      <Route path="article" element={
    
    <Article />} />
    </Route>
    <Route path='/login' element={
    
    <Login />}></Route>
    //当所有路径都没有匹配到时,兜底匹配
    <Route path="*" element={
    
    <NotFound />}></Route>
  </Routes>
</BrowserRouter>

5. Centralized routing configuration

Scenario: When we need routing authority control points, we need to filter the authority of the routing array. The so-called centralized routing configuration is to use an array to uniformly write all the routing correspondences to replace the original Roues component.

import {
    
     BrowserRouter, Routes, Route, useRoutes } from 'react-router-dom'

import Layout from './pages/Layout'
import Board from './pages/Board'
import Article from './pages/Article'
import NotFound from './pages/NotFound'

// 1. 准备一个路由数组 数组中定义所有的路由对应关系
const routesList = [
  {
    
    
    path: '/',
    element: <Layout />,
    children: [
      {
    
    
        element: <Board />,
        index: true, // index设置为true 变成默认的二级路由
      },
      {
    
    
        path: 'article',
        element: <Article />,
      },
    ],
  },
  // 增加n个路由对应关系
  {
    
    
    path: '*',
    element: <NotFound />,
  },
]

// 2. 使用useRoutes方法传入routesList生成Routes组件
function WrapperRoutes() {
    
    
  let element = useRoutes(routesList)
  return element
}

function App() {
    
    
  return (
    <div className="App">
      <BrowserRouter>
        {
    
    /* 3. 替换之前的Routes组件 */}
        <WrapperRoutes />
      </BrowserRouter>
    </div>
  )
}

export default App

Guess you like

Origin blog.csdn.net/qq_37967853/article/details/127922056