Detailed explanation of the use of Router6 in React

Premise: This document mainly describes the use of router6 in functional components

1. The use of router6

download

npm install react-router-dom

index.js file

// 从 react-dom/client 引入 ReactDOM
import ReactDOM from 'react-dom/client'
//引入BrowserRouter
import {
    
     BrowserRouter } from 'react-router-dom'
import App from './App'
ReactDOM.createRoot(document.getElementById('root')).render(
  <BrowserRouter>
    <App />
  </BrowserRouter>
)

In <BrowserRouter>addition <HashRouter>, the difference between the two is as follows:

1. The underlying principles are different:

​ BrowserRouter uses the history API of H5

​ HashRouter uses the hash value of the URL

2. The expression of path is different

​ There is no # in the path of BrowserRouter, such as localhost:3000/add

​ The path of HashRouter contains #, for example localhost:3000/#/add

3. The impact on routing state parameters after refresh

​ BrowserRoute has no effect because the state is stored in the history object

​ The routing state parameter is lost after the HashRouter is refreshed

How to create routes

1. Basic use of routing

import {
    
     NavLink, Routes, Route, Navigate } from 'react-router-dom'
import About from './components/About.jsx'
import Home from './components/home.jsx'
import Children from "../components/children.jsx"

export default function App() {
    
    
  return (
    <div>
       <NavLink to="/home">Home</NavLink>
      <NavLink to="/about">About</NavLink>
      <Routes>
        <Route path="/home" element={
    
    <Home />}>
            {
    
    /*嵌套路由(子路由)*/}
            <Route path="/about" element={
    
    <About />}></Route>
        </Route>
        <Route path="/about" element={
    
    <About />}></Route>
        <Route path="/" element={
    
    <Navigate to="/home" />}></Route>
      </Routes>
    </div>
  )
}

<Navigate>: As long as <Navigate>the component is rendered, the path will be modified and the view will be switched. It can be used for routing redirection, setting the default routing page for entering the page.

2. Create a routing table

// 路由表
// routes/index.js
import {
    
     Navigate } from 'react-router-dom'
import About from '../components/About.jsx'
import Home from '../components/home.jsx'
import Children from "../components/children.jsx"
import 
const routes = [
    //路由重定向
    {
    
    
    path: '/',
    element: <Navigate to="/home" />,
  },
  {
    
    
    path: '/home',
    element: <Home />,
     //创建子路由
      children:[
      {
    
    
      path:"children",
      element:<Children/>
       }
      ]
  },
  {
    
    
    path: '/about',
    element: <About/>,
  },
  
]

export default routes

Mount the route in App.jsx

//App.jsx
import {
    
     NavLink,useRoutes} from 'react-router-dom'
import About from './components/About.jsx'
import Home from './components/home.jsx'
//引入路由表
import routes from './router';
export default function App() {
    
    
    //生成路由规则
    const route=useRoutes();
  return (
    <div>
       <NavLink to="/home">Home</NavLink>
      <NavLink to="/about">About</NavLink>
      <div className="content">
      //在要显示路由页面的地方挂载路由
           {
    
    route}
      </div>
    </div>
  )
}

Nested routes (sub-routes)

import React, {
    
     Fragment } from 'react'
import {
    
     NavLink,Outlet} from 'react-router-dom'
export default function Home() {
    
    
  return (
    <Fragment>
       <NavLink to="/home/children">children</NavLink>
       <Outlet/>
    </Fragment>
  )
}

<Outlet>: Set the exit of the sub-routing, that is, where to render the sub-routing

2. Routing parameters

Pass the params parameter

Declare params when registering routes

 {
    
    
    path: '/about /:id',
    element: <About/>,
  },

pass parameters

<NavLink to={
    
    `/about/children/${
    
    id}>children</NavLink>

Use useParms() to receive parameters

import React from 'react'
import {
    
     useParams} from 'react-router-dom'
export default function Children() {
    
    
   const {
    
    id}=useParams();
  return (
    <div>About:{
    
    id}</div>
  )
}

Pass the search parameter

register

{
    
    
    path: '/about',
    element: <About/>,
  },

pass parameters

<NavLink to={
    
    `/about/children?id=${
      
      id}&message=${
      
      message}`}>children</NavLink>

Use useSearchParams()to receive parameters. The method returns an array with two elements: searchthe parameter and searchthe method that modifies the parameter.

import React from 'react'
import {
    
     useSearchParams } from 'react-router-dom'
export default function Children() {
    
    
  const [searchParams,setSearchParms]=useSearchParams();
    //获取相对应的值
    const id=searchParams.get('id');
    const message=searchParams.get('message');
    function change() {
    
    
    setSearchParams('id=2&message=ccc')
  }
  return (
    <div>About
      {
    
    id}:{
    
    message}
      <button onClick={
    
    change}>Change search params</button>
      </div>
  )
}

Pass the state parameter

register

{
    
    
    path: '/about',
    element: <About/>,
  },

pass parameters

<NavLink to="/about/children" state={
    
    {
    
    id:id,message:message}}>children</NavLink>

Use useLocation()to receive parameters. This method returns locationthe object of the routing component

import React from 'react'
import {
    
     useParams} from 'react-router-dom'
export default function Children() {
    
    
  const {
    
    
    state: {
    
     id,message },
  } = useLocation();
  return (
    <div>{
    
    id}:{
    
    message}</div>
  )
}

useLocation() contains the content as shown below

image-20221113105814429

3. Routing jump

method one

 <NavLink to="/home">Home</NavLink>

Method 2: useNavigate()

import React, {
    
     Fragment } from 'react'
import {
    
     NavLink,Outlet,useNavigate} from 'react-router-dom'
export default function Home() {
    
    
    const navigate=useNavigate();
    const linkTo=()=>{
    
    
        navigate("/home/children",{
    
    
            replace:false,
            state:{
    
    
                id:id,
                message:message
            }
        })
    }
    const back=()=>{
    
    
        //后退
        navigate(1);
        //前进
        //navigate(-1);
    }
  return (
    <Fragment>
      <Button onClick={
    
    linkTo}>children</Button>
      <Button onClick={
    
    back}>children</Button>  
       <Outlet/>
    </Fragment>
  )
}

useNavigate()Returns a function that can be called to implement programmatic route navigation. There are two ways to pass parameters to a function.

The first way passes two parameters: route and related parameters. Parameters can only be set replaceand state. Want to pass the paramsand searchparameters directly on the route strip.

The second way passes a number representing a few steps forward or backward.

Guess you like

Origin blog.csdn.net/CYL_2021/article/details/127829929
Recommended