react-router-dom V6 Chinese documentation tutorial summary

The latest Vue project learning video recorded personally: Station B

Little Fat Mei-'s Personal Space_哔哩哔哩_Bilibili

Table of contents

1. Comparison with V5 routing

2. Routing steps

2.1 Import library files

2.2 Introduction of Router on the homepage

2.3 Routing usage

One-level routing and multi-level routing

2.4 Redirection

Use the Navigate component instead

2.5 Nested routing

2.6 Declarative and programmatic navigation

2.6.1 Declarative Navigation

2.6.2 Programmatic navigation (note that HOOK uses class components and cannot be used directly)

2.7 Dynamic Routing

​edit

2.8 useRoutes hook configuration routing


1. Comparison with V5 routing


< Route > Feature Changes

path: matches the URL corresponding to the current page.

element: Added , used to determine which component to render when the route is matched. Replace v5's component and render.

<Routes> replaces <Switch>

<Outlet></Outlet> makes nested routing easier

useNavigate instead of useHistory

Removed activeClassName and activeStyle of <NavLink/>

Hook useRoutes instead of react-router-config

removed exact 

Routing official website: https://reactrouter.com/en/v6.3.0/api

2. Routing steps

2.1 Import library files

Bring in the latest reac-router-dom

yarn

$ yarn add react-router-dom@6

npm

$ npm install react-router-dom@6

At present, the default installation of the react project is already the v6 version, no need to add a special version number

2.2 Introduction of Router on the homepage

What I introduced here is HashRouter, and there is also a BrowserRouter

import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import { BrowserRouter,HashRouter } from "react-router-dom";
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
    <BrowserRouter>
    <App />
    </BrowserRouter>
    
);

2.3 Routing usage

One-level routing and multi-level routing

<Routes>
  {/*<Route path="/" element={<Film/>}/>*/}
  <Route index element={<Film/>}/> 
  <Route path="/film" element={<Film/>}/>
  <Route path="/cinema" element={<Cinema/>}/>
  <Route path="/center" element={<Center/>}/>
</Routes>
  • index is used for nested routes, only when matching the parent route, set the rendered component.
  • To solve the problem that when a nested route has multiple sub-routes but cannot confirm which sub-route is rendered by default, the index attribute can be added to specify the default route.

2.4 Redirection

Use the Navigate component instead

<Routes>
  <Route path="/film" element={<Film />} />
  <Route path="/cinema" element={<Cinema />} />
  <Route path="/center" element={<Center />} />
  <Route path="*" element={<Navigate to="/film" />} />
</Routes>

2.5 Nested routing

<Route path="/film" element={<Film/>}>
  {/* <Route index  element={<Nowplaying/>}/> */}
  <Route path="" element={<Redirect to="/film/nowplaying"/>}/>
  <Route path="nowplaying" element={<Nowplaying/>}/>
  <Route path="comingsoon" element={<Comingsoon/>}/>
</Route>

// Film组件 <Outlet /> 相当于 <router-view />

2.6 Declarative and programmatic navigation

2.6.1 Declarative Navigation

<NavLink to='/'>首页</NavLink> |
<NavLink to='/news'>新闻</NavLink> | 
<NavLink to='/about'>我的</NavLink> | 
<NavLink to='/detail/123'>详情界面</NavLink>

2.6.2 Programmatic navigation (note that HOOK uses class components and cannot be used directly)

// url传参
const navigate = useNavigate()
navigate(`/detail?id=${id}`)
// 获取url参数
import { useSearchParams } from 'react-router-dom'

const [searchParams, setSearchParams] = useSearchParams()
// 获取参数
searchParams.get('id')
// 判断参数是否存在
searchParams.has('id')
// 同时页面内也可以用set方法来改变路由
setSearchParams({"id":2})

2.7 Dynamic Routing

// 跳转页面,路由传参
navigate(`/detail/${id}`)

// 配置动态路由
<Route path="/detail/:id" element={<Detail />}/>
    
// 获取动态路由参数
import { useParams } from 'react-router-dom'  
const { id } = useParams()

Found that props is an empty object! ! ! Such many functions cannot be realized through routing parameters at all, such as:

Programmatic routing navigation, you can use the useNavigate hook for navigation in uncontrolled components, but there is nothing you can do in class components, you can only find a way to use the <Navigate> tag, which is very troublesome, you can read this article: https: //www.jianshu.com/p/5bdfd2fac2cd
Get routing parameters. In the previous version of react-router-dom, the three routing parameters location, history, and match are directly mounted on the props of the component, even if the component is not Routing components can also use withRouter high-level components to enhance ordinary components, or bring these three parameters to props.

In v6 version withRouter is directly removed. what to do?
It is estimated that the official purpose is to strongly recommend that we use React Hooks , so as to increase the threshold for using class components (tm can't be compatible like vue, smooth transition?). You can only write the high-level component withRouter yourself to achieve this requirement. You can read the answer in this article: https://cloud.tencent.com/developer/ask/sof/296970

// 获取动态路由参数
import { useNavigate,useLocation,useParams } from 'react-router-dom'  

export function withRouter( Child ) {
    return ( props ) => {
      const location = useLocation();
      const navigate = useNavigate();
      const params = useParams()
    //   const match= useMatch()
      return <Child params={params}  navigate={ navigate } location={ location } />;
    }
  }
  

 When the component is used

import React, { Component } from 'react'
// 获取动态路由参数
import {withRouter} from './withRouter'
 class Detail extends Component {
   constructor(){
    super()
   }
  render() {
    console.log(this);
    return (
      <div>Detail
        <p>参数:{this.props.params.id}</p>
      </div>
    )
  }
}
export default withRouter(Detail)

App.js component routing configuration

import Home from './views/Home'
import News from './views/News'
import About from './views/About'
import One from './views/Today'
import Two from './views/Yestoday'
import Detail from './views/Detail'
import './app.css'
//配置路由
import { Route, Link, Routes, BrowserRouter,NavLink,Navigate ,Outlet} from 'react-router-dom'
function App() {
  return (
    <>
        <div>
          <NavLink to='/'>首页</NavLink> |
          <NavLink to='/news'>新闻</NavLink> | 
          <NavLink to='/about'>我的</NavLink> | 
          <NavLink to='/detail/123'>详情界面</NavLink>
          <Outlet/>
        </div>

        <Routes>
          {/* <Route path="/" element={<Home />}></Route> */}
          <Route index element={<Home />}></Route>
          <Route path="home" element={<Home />}></Route>
           {/* // 配置动态路由 */}
           <Route path="detail/:id" element={<Detail />}/>
           {/* 路由嵌套 */}
          <Route path="news" element={<News />}>
             {/* 二级路由 */}
             {/* 
             index用于嵌套路由,仅匹配父路径时,设置渲染的组件。
              解决当嵌套路由有多个子路由但本身无法确认默认渲染哪个子路由的时候,可以增加index属性来指定默认路由。
              index路由和其他路由不同的地方是它没有path属性,他和父路由共享同一个路径。
              */}
            <Route index element={<One/>}></Route>
            <Route path='one' element={<One/>}></Route>
            <Route path='two' element={<Two />}></Route>
          </Route>
          <Route path="about" element={<About />}></Route>
          {/* //当输入  /* 任意信息,重定向到首页 */}
          <Route path='*' element={<Navigate replace to="/home" />} />
        </Routes>
    </>
  );
}

export default App;

style

In V6 version activeClassName  and activeStyle  have been removed from NavLinkProps , you can directly use a function in the className and style of <NavLink> to use active .

Usage of className:

V5:

<NavLink to="/faq" activeClassName="selected">
  FAQs
</NavLink>

V6

let activeClassName = "underline"
<NavLink
	to="/faq"
	className={({ isActive }) =>
	  isActive ? activeClassName : undefined
	}
>
  FAQs
</NavLink>

2.8 useRoutes hook configuration routing

import React from "react";
import Layout from '../views/Layout'
import Home from '../views/Home'
import News from '../views/News'
import About from '../views/About'
import One from '../views/Today'
import Two from '../views/Yestoday'
import Detail from '../views/Detail'

const routes=[
    {
        path:'/',
        element:<Layout/>,
        children:[
            {
                path:'/',
                element:<Home/>,
            },
            {
                path:'/detail/:id',
                element:<Detail/>,
            },
            {
                path:'/about',
                element:<About/>,
            },
            {
                path:'/news',
                element:<News/>,
                children:[
                    { index: true, element: <One /> },
                    {  path: "one", element: <One /> },
                    { path: "two", element: <Two /> }
                ]
            }
        ]

    }
]

export default routes

app.js uses


import { useRoutes } from "react-router-dom";
import routes from './router/routes'
function App() {
  const element = useRoutes(routes);

  return (
   <>
    {element}
    </>

  );
}

export default App;

Three, react-router-dom upgrade v6 content

Switch -> Routers

Router component -> element

<Route path='/admin/dashboard' component={Dashboard} />
<Route path=":id" element={<UserProfile />} />


redirect
 

//v5
<Redirect to="about" />
<Redirect to="home" push />

// v6
<Navigate to="about" replace />
<Navigate to="home" />


Router can directly nest Router,
which was not possible before. You need to define sub-routes in a component


Simplified routing path rules


useHistory becomes History

v5

let history = useHistory();
function handleClick() {
  history.push("/home");
}

v6

let navigate = useNavigate();
function handleClick() {
  navigate("/home");
}
//v5
const { go, goBack, goForward } = useHistory();
//v6
const navigate = useNavigate();
<button onClick={() => navigate(1)}>
<button onClick={() => navigate(2)}>
<button onClick={() => navigate(-1)}>
<button onClick={() => navigate(-2)}>

重命名 <NavLink exact> to <NavLink end>
useMatch -> useRouteMatch

Guess you like

Origin blog.csdn.net/xm1037782843/article/details/127454966