Article Directory
React Router 6
overview
React Router is published on npm in three different packages, they are:
- react-router: The core library of routing, which provides a lot: components, hooks.
- react-router-dom: Contains all content of react-router, and adds some components dedicated to DOM, such as
<BrowserRouter>
etc. - react-router-native: Include all content of react-router, and add some APIs dedicated to ReactNative, such as:
<NativeRouter>
etc.
Variety
What has changed compared to React Router 5.x versions?
-
Changes to built-in components: removed
<Switch/>
, added,<Routes/>
etc. -
Changes in syntax:
component={About}
changed toelement={<About/>}
etc. -
Added multiple hooks:
useParams
,useNavigate
,useMatch
etc. -
The official recommendation is to use functional components
document
Official website address: https://reactrouter.com/
Routing steps
Step 1: Install
react-router-dom is a library based on the react-router library on the browser side, so after installing this, you don't need to manually install react-router
npm install react-router-dom
npm install react-router-dom@^6.10.0
Step 2: Connect the Router
Link your App to the browser's URL. Wrap the BrowserRouter around your App
// index.js
import { BrowserRouter } from 'react-router-dom';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<BrowserRouter>
<App />
</BrowserRouter>
);
Step 2: Routing table configuration
//路由表配置:src/routes/index.jsx
import { Navigate } from 'react-router-dom';
import Home from '../views/Home';
import Friend from '../views/Friend';
import Setting from '../views/Setting';
import NotFound from '../views/NotFound';
import Chat from '../views/Chat';
const routes = [
// Navigate 重定向
{ path: '/', element: <Navigate to='/home' /> },
{ path: '/home', element: <Home /> },
{
path: '/friend',
element: <Friend />,
children: [{ path: 'chat/:name', element: <Chat /> }],
},
{ path: '/setting', element: <Setting /> },
{ path: '*', element: <NotFound /> },
];
export default routes;
Step 4: Register routing and configure routing links
Register routes in src/App.jsx
, add links and global navigation.
// App.jsx
import { useState } from 'react';
import './App.css';
import { NavLink, useRoutes } from 'react-router-dom';
import routes from './routes';
const App = () => {
// 根据路由表生成对应的路由规则
const ElementRouter = useRoutes(routes);
const [items] = useState([
{ path: '/home', title: '首页' },
{ path: '/friend', title: '好友' },
{ path: '/setting', title: '设置' },
]);
return (
<div className='app'>
<nav className='nav'>
<div className='w'>
{/* 路由链接 */}
{items.map(item => (
<NavLink className={({ isActive }) => (isActive ? 'active' : '')} to={item.path} key={item.path}>
{item.title}
</NavLink>
))}
</div>
</nav>
{/* 注册路由 */}
{ElementRouter}
</div>
);
};
export default App;
Step 5: Create a routing component
Routing components are placed in the views or pages file in the src directory
route monitoring
// 监听路由的变化
const location = useLocation();
useEffect(() => {
console.log('进入:', location.pathname);
return () => {
console.log('离开:', location.pathname);
};
});
Use programmatic navigation (here is the 6 version of react-route-dom, different versions will be different, Baidu by yourself)
npm install react-router-dom@^6.10.0
import {
useNavigate } from "react-router-dom";
//跳转页面
let history = useNavigate();
history("/friend", {
state: {
id: 1 } }); //跳转页面并携带一个id参数,格式必须如上state不能省略,参数都放在state下面
Complete code example
jump routing
import {
useNavigate } from "react-router-dom";
export default function Home() {
let history = useNavigate();
const xj = () => {
//在这个代码里,跳转friend页面并携带了id:1的参数
history("/friend", {
state: {
id: 1 } });
};
return (
<div>
<p onClick={
xj}>跳转friend页面</p>
</div>
);
}
Receive parameters
import {
useLocation } from "react-router-dom";
export default function Friend() {
let a = useLocation();
console.log('a',a)
let id = a.state.id;
return <p>---{
id}</p>;
}
The print result of a is as follows, and the required parameters are in the red box
Three ways to pass parameters in react
1 Routing fixed----navlink pass value params pass parameter useParams
//路由
import {
Outlet,NavLink } from 'react-router-dom'
{
path:'detail/:id/:title/:content',
element:<Detail />
}
//组件内点击
<li>
<NavLink to={
`detail/${
item.id}/${
item.title}/${
item.content}`} >{
item.title}</NavLink>
</li>
//组件内接受参数
import {
useParams } from 'react-router-dom'
export default function Detail() {
let {
id,title,content} = useParams()
return (
<div>
<ul>
<li>新闻id:{
id}</li>
<li>新闻标题:{
title}</li>
<li>新闻内容:{
content}</li>
</ul>
</div>
)
}
2 route pass value query pass parameter useSearchParams
//路由
import {
Outlet,NavLink } from 'react-router-dom'
{
path:'detail',
element:<Detail />
}
//组件内点击
<li>
<NavLink to={
`detail?id=${
item.id}&title=${
item.title}&content=${
item.content}`}>{
item.title}</NavLink>
</li>
//组件内接受参数 第一个参数传递过来的数据对象,用get方法来取值 第二个参数是设置新的数据
import {
useSearchParams } from 'react-router-dom'
export default function Detail() {
let [searchParams,setobj] = useSearchParams()
let id = searchParams.get('id')
let title = searchParams.get('title')
let content = searchParams.get('content')
return (
<div>
<ul>
<li>新闻id:{
id}</li>
<li>新闻标题:{
title}</li>
<li>新闻内容:{
content}</li>
<li onClick={
()=>{
setobj( {
id: 4, title: "你是谁啊4", content: "有什么事情啊4" })
}}>点击切换</li>
</ul>
</div>
)
}
3.state传参 useLocation
//路由
import {
Outlet,NavLink } from 'react-router-dom'
{
path:'detail',
element:<Detail />
}
//组件内点击
<li>
<NavLink to='detail' state={
item}>{
item.title}</NavLink>
</li>
// state传参
import React from 'react'
import {
useLocation } from 'react-router-dom'
export default function Detail() {
let {
state:{
id,title,content}} = useLocation()
return (
<div>
<ul>
<li>新闻id:{
id}</li>
<li>新闻标题:{
title}</li>
<li>新闻内容:{
content}</li>
</ul>
</div>
)
}
Programmatic navigation parameter passing and jumping
searchParams pass parameters
Login.js #Jump to the detail page and pass parameters
// 1.导入useNavigate
import {
useNavigate } from 'react-router-dom'
function Login () {
// 2.执行useNavigate得到一个跳转函数
const navigate = useNavigate()
function goDetail () {
// 3.调用跳转函数传入目标路径
navigate('/detail?id=10&name=cp', {
replace: true })
}
return (
<div>
<p>login</p>
<button onClick={
goDetail}>跳转Detail</button>
</div>
)
}
Detail.js #get parameters
//取参
import {
useSearchParams } from 'react-router-dom'
function Detail () {
const [params] = useSearchParams()
const id = params.get('id')
const name = params.get('name')
return (
<div>
Detail路径传的参数id:{
id},name:{
name}
</div>
)
}
Params passing parameters
Login.js #Jump to the detail page and pass parameters
// 1.导入useNavigate
import {
useNavigate } from 'react-router-dom'
function Login () {
// 2.执行useNavigate得到一个跳转函数
const navigate = useNavigate()
function goDetail () {
// 3.调用跳转函数传入目标路径
navigate('/detail/1001', {
replace: true })
}
return (
<div>
<p>login</p>
<button onClick={
goDetail}>跳转Detail</button>
</div>
)
}
Detail.js #get parameters
import {
useParams } from 'react-router-dom'
function Detail () {
const params = useParams()
const id = params.id
return (
<div>
Detail路径传的参数id:{
id}
</div>
)
}