react路由使用
在介绍 React Router 的概念以前,需要先区分两个概念:
react-router:为 React 应用提供了路由的核心功能;
react-router-dom:基于 react-router,加入了在浏览器运行环境下的一些功能。
1. 安装(本文6.22.3版本)
npm i react-router-dom -S
2. 创建router/index.js
import Goods from "../page/Goods" import Me from "../page/Me" import App from "../App" import {createBrowserRouter} from 'react-router-dom' const router = createBrowserRouter([ { path:'/', element:<App/> }, { path:'/goods', element:<Goods/> }, { path:'/me', element:<Me/> }, ]) export default router
3. 在入口index.js文件中注入
import {RouterProvider} from 'react-router-dom' import router from './router' root.render( <React.StrictMode> <Provider store={store}> <RouterProvider router={router}></RouterProvider> </Provider> </React.StrictMode> );
4.路由跳转
4.1 通过Link标签
import {Link, useNavigate} from 'react-router-dom'
<Link to="/goods">跳转Goods页面</Link>
4.2 编程式导航 useNavigate
const navigate = useNavigate()
<button onClick={()=>navigate('/me')}>跳转Me页面</button>
5. 查询参数接收
<Link to="/goods?id=1111">跳转Goods页面</Link> import {useSearchParams} from 'react-router-dom' export function Goods(){ const [params] =useSearchParams() const id = params.get('id') // 获取参数 return( <div>Goods id: {id}</div> ) } export default Goods
6. 404配置
{ path:'*', element:<NotFound/> },
7.嵌套路由, children配置嵌套关系<Outlet/>子路由显示位置
// 配置 { path:'/', element:<Layout/>, children:[ { index:true,// 默认 element:<App/> }, { path:'/goods', element:<Goods/> }, { path:'/me', element:<Me/> }, ] }, // 布局文件 import {Outlet} from 'react-router-dom' import AsideMenu from './AsideMenu' import './layout.css' export function Layout(){ return( <div> <div className='header'>header</div> <div className='container'> <div className='aside'> <AsideMenu></AsideMenu> </div> <div className='main'> {/* 子路由显示位置 */} <Outlet></Outlet> </div> </div> </div> ) } export default Layout