概述
十分钟带你理解 React18项目如何在路由跳转时携带参数,如何获取路由地址中携带的参数。
一、定义路由表
1.1 装包
npm install react-router-dom --save
1.2 定义路由文件
import React from 'react'
// 关键代码
import { createBrowserRouter } from 'react-router-dom'
// 引入组件,没啥好说的
import MainLayout from '../pages/layouts/MainLayout'
import ManageLayout from '../pages/layouts/ManageLayout'
import QuestionLayout from '../pages/layouts/QuestionLayout'
import Home from '../pages/Home'
import NotFond from '../pages/NotFound'
import List from '../pages/manage/List'
import Edit from '../pages/question/Edit'
// 写法与 Vue.js 类似
const router = createBrowserRouter([
{
path: '/',
element: <MainLayout />,
children: [
{
path: '/',
element: <Home />,
},
{
path: 'manage',
element: <ManageLayout />,
children: [
{
path: 'list',
element: <List />,
},
],
},
{
path: '*', // 404 路由配置都写在最后,起到一个兜底的作用
element: <NotFond />,
},
],
},
{
path: 'question',
element: <QuestionLayout />,
children: [
{
path: 'edit/:id',
element: <Edit />,
},
],
},
])
export default router
二、路由跳转
2.1 跳转到某个地址
import React, { FC } from 'react'
import { useNavigate, Link } from 'react-router-dom'
const Home: FC = () => {
const nav = useNavigate()
// 点击登录
function handleLogin() {
/** 方式一:*/
// nav('/login') || nav('/login?a=10')
/** 方式二:*/
nav({
pathname: '/login',
search: 'b=20',
})
}
return (
<div>
// 方式一:
<button onClick={handleLogin}>登录</button>
// 方式二:
<Link to="/register?a=10">注册</Link>
</div>
)
}
export default Home
2.2 路由返回
import React, { FC } from 'react'
import { useNavigate } from 'react-router-dom'
const Login: FC = () => {
const nav = useNavigate()
return (
<div>
{/* nav(-1) -- 路由跳转后可以实现返回 */}
<button onClick={() => nav(-1)}>返回</button>
</div>
)
}
export default Login
三、如何获取路由参数
3.1 解析动态路由参数
路由定义时,使用动态路由:
{
path: 'question',
element: <QuestionLayout />,
children: [
{
path: 'edit/:id',
element: <Edit />,
},
],
},
获取路由传参:
import React, { FC } from 'react'
// 核心代码
import { useParams } from 'react-router-dom'
const Edit: FC = () => {
// 拿到路由传参
const { id = '' } = useParams()
return (
<div>
<div>{id}</div>
</div>
)
}
export default Edit
3.2 解析URL参数
import React, { FC, useState } from 'react'
// 核心代码
import { useSearchParams } from 'react-router-dom'
const List: FC = () => {
// 核心代码
const [searchParams] = useSearchParams()
console.log('key word', searchParams.get('keyword'))
return (
<>
...其他代码
</>
)
}
export default List