react-router-dom的使用
1.安装
npm i react-router-dom
2.定义路由
element的值是定义好的组件
import {createBrowserRouter} from 'react-router-dom'
const router = createBrowserRouter(
[
{
path:'/',
element: <Layout />,
children: [
{
path: 'A',
element: <A/>
},
{
path: 'B/:id/:name',
element: <B />
}
]
},
{
path:'/Login',
element: <Login/>,
},
]
)
export default router
3.加载路由
import { RouterProvider } from 'react-router-dom';
<RouterProvider router={router} />
4.使用路由
声明式导航
跳转定义
<Link to="/Login">
//传参
<Link to="/B/1/DGDH">
参数接收
const [params] = useSearchParams()
let id = params.get('id')
编程式导航
跳转定义,使用useNavigate
const navigate = useNavigate()
navigate('/Login')
navigate('/B/1/DGDH')
参数接收
const params = useParams()
let id = params.id
5.嵌套路由
默认下级路由用index:true,代替path:‘’,
需要在父级组件中添加加载子路由内容
import {createBrowserRouter} from 'react-router-dom'
const router = createBrowserRouter(
[
{
path:'/',
element: <Layout />,
children: [
{
index:true,
element: <A/>
},
{
path: 'B/:id/:name',
element: <B />
}
]
},
{
path:'/Login',
element: <Login/>,
},
]
)
export default router
const Layout = () => {
return (
<div className="layout">
<div className="container">111111</div>
<Outlet />
</div>
}
export default Layout
6.404路由配置
路由表配置的末尾添加
import {createBrowserRouter} from 'react-router-dom'
const router = createBrowserRouter(
[
{
path:'/',
element: <Layout />,
children: [
{
index:true,
element: <A/>
},
{
path: 'B/:id/:name',
element: <B />
}
]
},
{
path:'/Login',
element: <Login/>,
},
{
path:'*',
element: <NotFount />
}
]
)
export default router
7.两种路由模式
- history模式(createBrowerRouter)
需要后端支持
原理:history对象+ pushState事件 - hash模式(createHashRouter)
不需要后端支持以#拼接地址
原理:监听hashChange事件