React Router 6 Quick Start

React Router 6 is the v6 version of react-router-dom. This version is already the default version when create-react-app creates a react project. This article mainly records the basic usage and common API of the v6 version, and will make some comparisons with v5:

For more details, please refer to: React Router Chinese Documentation

npm install

If React Router has not been installed in the project, you can perform the following NPM installation, and the v6 version is installed by default:

npm i react-router-dom

Component

The following is an introduction to commonly used components in react-router-dom v6:

 <BrowserRouter>与<HashRouter>

The <BrowserRouter> component is used to wrap the entire application area that needs to use routing components ( generally used to wrap the entire <App /> ) . It also indicates that the current routing mode is BrowserRouter mode. In addition to using <BrowserRouter>, you can also use <HashRouter > Component, with the same usage, it indicates that the current routing mode is HashRouter (specifically, a /# will appear in the address bar of the page )

 Note: The usage of <BrowserRouter> and <HashRouter> in v6 is the same as in v5 .

Code example:

import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App'
// 引入路由模式的包裹组件 BrowserRouter / HashRouter
import { BrowserRouter } from 'react-router-dom'

const root = ReactDOM.createRoot(document.getElementById('root'))
root.render(
  <BrowserRouter>
    <App />
  </BrowserRouter>

Note: Unless otherwise specified, the following components and APIs  are used by default in the application area wrapped by the above <BrowserRouter> or <HashRouter> components!

<Routes>与<Route>

 In the v6 version, the previous Switch component was removed and a new replacement was introduced: <Routes>;

<Routes> and <Route> need to be used together, and <Routes> must be used to wrap <Route> (Note: Even if there is only one <Route>, <Routes> needs to be wrapped, and <Routes> cannot be omitted!);

<Route> is used to configure the corresponding mapping relationship between the routing path path and the component element, as long as the path matches the current URL (the default is non-strict mode), the component configured by element will be rendered;

<Route caseSensitive >: The caseSensitive attribute is used to specify whether the matching path is case-sensitive , and the default is false;

<Route> can also be nested, and can be used in conjunction with useRoutes() to configure the "routing table", but its sub-routes need to be rendered through the <Outlet> built-in component.

Code example - conventional writing:

// ...
import {NavLink, Routes, Route} from 'react-router-dom'
//...
export default function App() {
  return (
    <>
    <h1>App</h1>
    <hr />
    {/* 路由链接 */}
    <NavLink className="tab" to='/home'>Home</NavLink><br />
    <NavLink className="tab" to='/about'>About</NavLink><br />
    <hr />
    {/* 配置路由映射关系 */}
    <Routes>
      <Route path='/home' element={<Home/>} />
      <Route path='/about' element={<About/>} />
    </Routes>

    </>
  )
}

Code example - routing table writing method (new in v6):

Note: The following code is written in the src/routes/index.js file

// 此文件用于统一配置路由表
import {Navigate} from 'react-router-dom'
import Home from '../pages/Home'
import About from '../pages/About'

// 定义路由表
const routes =  [
  {
    path: '/home',
    element: <Home />,
    // 配置子路由,没有可以不写
    children: []
  },
  {
    path: '/about',
    element: <About />
  },
  // 仍旧配置路由重定向
  {
    path: '/',
    element: <Navigate to='/home' />
  }
]
// 导出
export default routes

Note: The data format type of each configuration item in the routing table list is as follows:

interface RouteObject {
    caseSensitive?: boolean;        // 是否区分大小写
    children?: RouteObject[];       // 是否配置嵌套路由
    element?: React.ReactNode;      // 路径映射的组件
    // 是否 URL 在仅匹配到父组件的 path 时展示出来,此值为 true 则此路由为索引路由,则 path 和 children 均不要写
    index?: boolean;
    path?: string;                  // 用于跳转时匹配的路径
}

Use routing table:

//...
import {NavLink, useRoutes} from 'react-router-dom'
// 导入自定义的统一的路由表
import router from './routes'

export default function App() {
  // 根据路由表生成对应的路由规则
  const routes = useRoutes(router)
  return (
    <>
    <h1>App</h1>
    <hr />
    {/* 路由链接 */}
    <NavLink className="tab" to='/home'>Home</NavLink><br />
    <NavLink className="tab" to='/about'>About</NavLink><br />
    <hr />
    {/* 配置路由映射关系 */}
    {/* 使用路由表的方式 */}
    {routes}
    </>
  )
}

Note: It is more recommended to use the wording of "routing table" , so that there are many routing configurations, the routing structure and mapping relationship can be seen from the routing configuration table, and the routing is easier to manage. Therefore, subsequent routing configurations will show the wording of "routing table".

<Link>与<NavLink>

Both <Link> and <NavLink> are used to modify the URL without sending a network request. They are mainly used for routing link jumps. The usage of the two is exactly the same. The to attribute specifies the target path to jump to . The difference is that <NavLink> can be used for Automatically realize the "highlight" effect of the link . If the current URL matches the value of the to attribute, the tag will automatically add an active class name to help us achieve the "highlight" effect of the selected item; the active class name can also be customized, but It is not very useful, if you need it, you can refer to the official document by yourself; if you only want the <NavLink> of the current child to be "highlighted" during multi-level routing, and the <NavLink> of the parent component is not "highlighted", you can give the parent Add the end attribute to the <NavLInk end> ​​component.

Sample code:

// ...
import {NavLink} from 'react-router-dom'

// ...
{/* 路由链接 */}
<NavLink className="tab" to='/home'>Home</NavLink><br />
<NavLink className="tab" to='/about'>About</NavLink><br />

<Navigate>

The <Navigate> built-in component can be mainly used as a route redirection or a default route. As long as the component is rendered, the current URL will be modified to the path specified by its to attribute, and the view is switched:

Code example - conventional writing:

import {Routes, Route, Navigate} from 'react-router-dom'
// ...
{/* 配置路由映射关系 */}
    <Routes>
      // ...
      {/* 使用 Navigate 组件进行路由重定向 */}
      <Route path='/' element={<Navigate to='/home' />} />
    </Routes>

Code example - routing table writing method: 

import {Navigate} from 'react-router-dom'
// ...
// 路由表中配置路由重定向
  {
    path: '/',
    element: <Navigate to='/home' />
  }

<Outlet>

Used to render its corresponding subsequent sub-routes when <Route> is nested (equivalent to the "placeholder" of sub-routes)

Code example:

// ...
import { Outlet } from 'react-router-dom'
// ...
return (
    <div>
        {/* ... */}
        {/* 放置二级路由显示位置的占位组件 */}
        <Outlet />
    </div>
  )
// ...

hooks

The following mainly introduces some commonly used hooks in the v6 version. For full information, please refer to the official

useRoutes()

When using the "routing table" method when configuring routing, you need to use useRoutes() to create the corresponding <Routes> and <Route> routing structures based on the "routing table";

Code example:

// ...
import { useRoutes } from 'react-router-dom'
// ...
// 导入自定义的统一的路由表
import router from './routes'

export default function App() {
  // 根据路由表生成对应的路由规则
  const routes = useRoutes(router)
  return (
    <>
    {/* ... */}
    {/* 使用路由表的方式 */}
    {routes}
    </>
  )
}

useNavigate()

The useNavigate() hook returns a function for programmatic navigation, receiving two parameters:

Parameter 1: You can specify the specific jump path, and it can be a number to indicate forward or backward

Parameter 2: an object: {replace: true/false, state:{}}

Code example:

// ...
import { useNavigate } from 'react-router-dom'
export default function Demo() {
  // 编程式导航
  const navigate = useNavigate()

  const back = () => {
    navigate(-1)    // -1 表示后退一页,可以是多页
  }

  const toDetail = id => {
    navigate('detail', {
      replace: true,
      state: {
        id
      }
    })

  }
  const go = () => {
    navigate(1)    // 1 表示前进一页
  }
  return (
    <div>
      <button onClick={()=> back}>后退</button>
      <button onClick={()=> toDetail(1)}>展示详情</button>
      <button onClick={()=> go}>前进</button>
    </div>
  )
}

useParams()

useParams() hook is used to receive parameters when routing params parameter passing, and returns the parameter object. Similar to match.params in v5

Note : The parameters passed in the params parameter will be displayed in the address bar, and the parameters to be passed need to be defined in the routing configuration:

// params 路由配置参数示例:
<Route path={/demo/:id} element={<Demo />}></Route>

Code example:

// 配置路由时提前预定义参数数量和每个参数的 key
<Route path="/foo/:id" element={<Demo />} />

// 接收参数:
import { useParams } from "react-router-dom";
export default function Demo() {
  const params = useParams();
  return (
    <div>
      <h1>{params.id}</h1>
    </div>
  );
}

useSearchParams()

The useSearchParams() hook is used to receive parameters when the route search passes parameters, and returns an array containing two values, the contents are: the current search parameters and the function to update the search. similar to useState() hook )

Note : When using search to pass parameters, the parameters will be displayed in the address bar, but the parameters that need to be passed do not need to be defined in the routing configuration

Code example:

import { useSearchParams } from "react-router-dom";

// 当前路径为 /Demo?id=1
function Demo() {
  // useSearchParams 返回一个包含两个参数的数组
  const [searchParams, setSearchParams] = useSearchParams();
  // 参数1.get(key) 用于获取 search 传递的对应 key 的值
  console.log(searchParams.get("id")); // 1
  
  return <div>Demo</div>;
}

useLocation()

The useLocation() hook is used to obtain the current location information , and is also used to obtain the parameters passed in the form of routing state , which is compared to the location attribute of the routing component in v5. Returns an object, the most common of which are pathname and state.

Note: The parameters passed by state will not be displayed in the address bar, and the parameters to be passed do not need to be defined in the routing configuration. Examples of writing:

// 路由跳转时通过 state 形式携带参数示例:
<Link to='detail' state={
   
   {id: msg.id,title: msg.title, content: msg.content}}>{msg.title}</Link>

Code example of using useLocation() to receive parameters:

// ...
// 使用 useLocation 获取路由参数以 state 方式传的参
import {useLocation} from 'react-router-dom'

export default function Detail() {
  // 接收 state 方式传递的参数
  const {state:{id, title, content}} = useLocation()
  return (
    <div>
      ...
    </div>
  )
}

The above is the basic use of the commonly used components and APIs of React Router v6. I hope it can help you get started with Route6 more quickly. For more information about React Router, please visit the official website .

Guess you like

Origin blog.csdn.net/qq_43551801/article/details/128082752