当前位置:网站首页>Router 6/ and the difference with router5
Router 6/ and the difference with router5
2022-07-01 06:38:00 【song854601134】
List of articles
React Router 6 Quick start
1. summary
React Router Publish to... In three different packages npm On , They are :
react-router: The core library of routing , A lot of : Components 、 hook .
react-router-dom: contain react-router All contents , And add some dedicated to DOM The components of , for example etc. .
react-router-native: Include react-router All contents , And add some dedicated to ReactNative Of API, for example : etc. .
And React Router 5.x Version comparison , What has changed ?
Changes in built-in components : remove
Changes in grammar :component={About} Turn into element={} etc. .
Add more hook:useParams、useNavigate、useMatch etc. .
The official clearly recommends functional components !!!
…
2.Component
1. <BrowserRouter>
- explain :
<BrowserRouter>Used to wrap the entire application . - Sample code :
import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter } from "react-router-dom";
ReactDOM.render(
<BrowserRouter>
{/* The overall structure ( Usually it is App Components ) */}
</BrowserRouter>,root
);
- explain : Same function as , But the change is in the address bar hash value . remarks :6.x In the version 、 The usage and 5.x identical .
- And
v6 The previous... Has been removed from the version, New substitutes have been introduced :.
and To be used in conjunction with , And must be wrapped .
Equivalent to one if sentence , If its path is the same as the current URL matching , Then its corresponding component .
Property is used to specify : Whether matching is case sensitive ( The default is false).
When URL When something changes , Will see all its children Element to find the best match and render the component .
You can also nest , And can cooperate useRoutes() To configure “ Routing table ” , But it needs to go through Component to render its child routes .
Sample code :
<Routes>
/*path Property is used to define the path ,element Property is used to define the component corresponding to the current path */
<Route path="/login" element={<Login />}></Route>
/* Used to define nested routes ,home It's level 1 routing , The corresponding path /home*/
<Route path="home" element={<Home />}>
/*test1 and test2 It's secondary routing , The corresponding path is /home/test1 or /home/test2*/
<Route path="test1" element={<Test/>}></Route>
<Route path="test2" element={<Test2/>}></Route>
</Route>
//Route Or not element attribute , This is used to show nested routes . The corresponding path is /users/xxx
<Route path="users">
<Route path="xxx" element={<Demo />} />
</Route>
</Routes>
4. <Link>
- effect : modify URL, And do not send network requests ( Routing links ).
- Be careful : The outside needs to be
<BrowserRouter>or<HashRouter>The parcel . - Sample code :
import { Link } from "react-router-dom";
function Test() {
return (
<div>
<Link to="/ route "> Button </Link>
</div>
);
}
5. <NavLink>
- effect : And
<Link>Similar components , And can realize navigation “ The highlighted ” effect . - Sample code :
// Be careful : NavLink The default class name is active, The following is the specified custom class
// Custom style
<NavLink
to="login"
className={({ isActive }) => {
console.log('home', isActive)
return isActive ? 'base one' : 'base'
}}
>login</NavLink>
/*
By default , When Home The sub components of are matched successfully ,Home Your navigation will also highlight ,
When NavLink To add the end After attribute , if Home The sub components of are matched successfully , be Home Navigation has no highlight effect .
*/
<NavLink to="home" end >home</NavLink>
6. <Navigate>
- effect : as long as
<Navigate>Component is rendered , Will modify the path , Switch views . replaceProperty is used to control the jump mode (push or replace, The default is push).- Sample code :
import React,{useState} from 'react'
import {Navigate} from 'react-router-dom'
export default function Home() {
const [sum,setSum] = useState(1)
return (
<div>
<h3> I am a Home The content of </h3>
{/* according to sum The value of determines whether to switch views */}
{sum === 1 ? <h4>sum The value of is {sum}</h4> : <Navigate to="/about" replace={true}/>}
<button onClick={()=>setSum(2)}> Point I will sum Turn into 2</button>
</div>
)
}
7. <Outlet>
- When
<Route>When nesting occurs , Render its corresponding subsequent sub routes . - Sample code :
// Generate corresponding routing rules according to the routing table
const element = useRoutes([
{
path:'/about',
element:<About/>
},
{
path:'/home',
element:<Home/>,
children:[
{
path:'news',
element:<News/>
},
{
path:'message',
element:<Message/>,
}
]
}
])
//Home.js
import React from 'react'
import {NavLink,Outlet} from 'react-router-dom'
export default function Home() {
return (
<div>
<h2>Home Component content </h2>
<div>
<ul className="nav nav-tabs">
<li>
<NavLink className="list-group-item" to="news">News</NavLink>
</li>
<li>
<NavLink className="list-group-item" to="message">Message</NavLink>
</li>
</ul>
{/* Specify the location where the routing component is rendered */}
<Outlet />
</div>
</div>
)
}
3.Hooks
1. useRoutes()
- effect : According to the routing table , Dynamically create
<Routes>and<Route>. - Sample code
// Routing table configuration :src/routes/index.js
import About from '../pages/About'
import Home from '../pages/Home'
import {Navigate} from 'react-router-dom'
export default [
{
path:'/about',
element:<About/>
},
{
path:'/home',
element:<Home/>
},
{
path:'/',
element:<Navigate to="/about"/>
}
]
//App.jsx
import React from 'react'
import {NavLink,useRoutes} from 'react-router-dom'
import routes from './routes'
export default function App() {
// Generate corresponding routing rules according to the routing table
const element = useRoutes(routes)
return (
<div>
......
{/* Registered routing */}
{element}
......
</div>
)
}
2. useNavigate()
- effect : Returns a function used to implement programmatic navigation .
- Sample code :
import React from 'react'
import {useNavigate} from 'react-router-dom'
export default function Demo() {
const navigate = useNavigate()
const handle = () => {
// The first way to use it : Specify the specific path
navigate('/login', {
replace: false,
state: {a:1, b:2}
})
// The second way to use it : Pass in a value to move forward or backward , Be similar to 5.x Medium history.go() Method
navigate(-1)
}
return (
<div>
<button onClick={
handle}> Button </button>
</div>
)
}
3. useParams()
- effect : Returns the current matching route
paramsParameters , Be similar to 5.x Mediummatch.params. - Sample code :
import React from 'react';
import { Routes, Route, useParams } from 'react-router-dom';
import User from './pages/User.jsx'
function ProfilePage() {
// obtain URL Brought from params Parameters
let { id } = useParams();
}
function App() {
return (
<Routes>
<Route path="users/:id" element={<User />}/>
</Routes>
);
}
4. useSearchParams()
- effect : Used to read and modify the current position URL The query string in .
- Returns an array containing two values , The contents are : Current seaech Parameters 、 to update search Function of .
- Sample code :
import React from 'react'
import {useSearchParams} from 'react-router-dom'
export default function Detail() {
const [search,setSearch] = useSearchParams()
const id = search.get('id')
const title = search.get('title')
const content = search.get('content')
return (
<ul>
<li>
<button onClick={()=>setSearch('id=008&title= ha-ha &content= Hee hee ')}> Click me to update the received search Parameters </button>
</li>
<li> Message number :{id}</li>
<li> Message title :{title}</li>
<li> The message content :{content}</li>
</ul>
)
}
5. useLocation()
- effect : Get current location Information , For standard 5.x Of the routing component in
locationattribute . - Sample code :
import React from 'react'
import {useLocation} from 'react-router-dom'
export default function Detail() {
const x = useLocation()
console.log('@',x)
// x Namely location object :
/*
{
hash: "",
key: "ah9nv6sz",
pathname: "/login",
search: "?name=zs&age=18",
state: {a: 1, b: 2}
}
*/
return (
<ul>
<li> Message number :{id}</li>
<li> Message title :{title}</li>
<li> The message content :{content}</li>
</ul>
)
}
6. useMatch()
- effect : Return the current matching information , For standard 5.x Of the routing component in
matchattribute . - Sample code :
<Route path="/login/:page/:pageSize" element={<Login />}/>
<NavLink to="/login/1/10"> Sign in </NavLink>
export default function Login() {
const match = useMatch('/login/:x/:y')
console.log(match) // Output match object
//match The object contents are as follows :
/*
{
params: {x: '1', y: '10'}
pathname: "/LoGin/1/10"
pathnameBase: "/LoGin/1/10"
pattern: {
path: '/login/:x/:y',
caseSensitive: false,
end: false
}
}
*/
return (
<div>
<h1>Login</h1>
</div>
)
}
useInRouterContext()
effect : If the component is in In the context of , be useInRouterContext The hook returns true, Otherwise return to false.useNavigationType()
effect : Returns the current navigation type ( How users come to the current page ).
Return value :POP、PUSH、REPLACE.
remarks :POP It means that the routing component is directly opened in the browser ( Refresh the page ).useOutlet()
effect : Used to render nested routes rendered in the current component .
Sample code :
const result = useOutlet()
console.log(result)
// If the nested route is not mounted , be result by null
// If the nested route is already mounted , Show nested routing objects
10.useResolvedPath()
- effect : Given a URL value , Analyze the :path、search、hash value .
6 and 5 The difference between
Differences between nested routes
5 The middle road is used by Switch ,6 of use Route Instead .
5 The parent component in the declares the child route :
<Switch>
<Route path="/about/one" element={<One />}></Route>
<Route path="/about/two" element={<Two />}></Route>
<Route path="/about/three" element={<Three />}></Route>
<Switch />*/}
6 The parent component in the declares the child route
<Routes>
<Route path="one" element={<One />}></Route>
<Route path="two" element={<Two />}></Route>
<Route path="three" element={<Three />}></Route>
</Routes>
Note that there , If the nested route is written in the parent route , Then pay attention to distinguish between react5 The difference between . stay react-router5 in . Matching of parent routes
/about Don't omit, And in App.js Where the parent component of Route Of path You don't need to write in Chinese*
The following passage is in 6 If a child component is declared in the parent component in ,App.js Where the parent component of Route Of path Do not write in * A warning will appear :
router.ts:11 You rendered descendant <Routes> (or called `useRoutes()`) at "/about" (under <Route path="/about">)
but the parent route path has no trailing "*". This means if you navigate deeper, the parent won't match anymore and therefore the child routes will never render.
Please change the parent <Route path="/about"> to <Route path="/about/*">
边栏推荐
猜你喜欢

Promise

自开发软件NoiseCreater1.1版本免费试用

On whether variables are thread safe

C language course is provided with employee information management system (large operation)

mysql学习

【Unity Shader 描边效果_案例分享第一篇】
![[enterprise data security] upgrade backup strategy to ensure enterprise data security](/img/59/e44c6533aa546e8854ef434aa64113.png)
[enterprise data security] upgrade backup strategy to ensure enterprise data security
![[unity shader stroke effect _ case sharing first]](/img/bd/5cd1bef24e6b6378854114c2c05bd9.png)
[unity shader stroke effect _ case sharing first]

Promise

产品学习(三)——需求列表
随机推荐
C language course set up library information management system (big homework)
【#Unity Shader#自定义材质面板_第二篇】
[ManageEngine Zhuohao] helps Julia college, the world's top Conservatory of music, improve terminal security
C语言课设学生考勤系统(大作业)
Several ways of gson's @jsonadapter annotation
Comment imprimer le tableau original
数据库笔记
[unity shader stroke effect _ case sharing first]
Chapitre V gestion des entrées / sorties
C语言课设学生信息管理系统(大作业)
C how to print out the original array
H5 web page determines whether an app is installed. If it is installed, it will jump to the summary of the scheme to download if it is not installed
C#如何打印輸出原版數組
Functions of switch configuration software
根据输入画有向图
【#Unity Shader#自定义材质面板_第一篇】
Postgraduate entrance examination directory link
3. Disabling copy construction
给逆序对数求原数组
[network security tool] what is the use of USB control software