`react-router-dom`是一个用于在 React 应用中实现路由功能的重要库
一、实现页面导航
1. 声明式路由定义
1.1 基本原理
使用`react-router-dom`可以在代码中直接定义一个路由规则,如从`/home`路径导航到`Home`组件。
1.2 代码示例
`Router` 路由根容器,`Routes` 包裹所有的路由规则,`Route` 定义了一条具体的路由,包括路径(`path`)和对应的组件(`element`)。
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";import Home from "./Home";import About from "./About";const App = () => {return (<Router><Routes><Route path="/home" element={<Home />} /><Route path="/about" element={<About />} /></Routes></Router>);};export default App;
2. 动态路由匹配
2.1 处理可变路径参数
可以定义一个路由路径为`/user/:id`,其中`:id`就是动态参数。
2.2 代码示例
import {BrowserRouter as Router,Route,Routes,useParams,} from "react-router-dom";const UserDetail = () => {const { id } = useParams();return (<div><h1>User Detail for ID: {id}</h1></div>);};const App = () => {return (<Router><Routes><Route path="/user/:id" element={<UserDetail />} /></Routes></Router>);};export default App;
二、嵌套路由和布局管理
1. 嵌套路由实现
1.1 构建多层级页面结构
例如:有一个父路由`/blog`,其下包含子路由`/blog/posts`(文章列表)和`/blog/post/:id`(单个文章详情)。
1.2 代码示例
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";import Blog from "./Blog";import BlogPosts from "./BlogPosts";import BlogPostDetail from "./BlogPostDetail";const App = () => {return (<Router><Routes><Route path="/blog" element={<Blog />}><Route path="posts" element={<BlogPosts />} /><Route path="post/:id" element={<BlogPostDetail />} /></Route></Routes></Router>);};export default App;
2. 布局管理与共享布局组件
2.1 统一布局应用
假设我们有一个名为`Layout`的布局组件,包含了导航栏和侧边栏。
2.2 代码示例
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";import Layout from "./Layout";import Home from "./Home";import About from "./About";const App = () => {return (<Router><Routes><Route path="/" element={<Layout />}><Route path="home" element={<Home />} /><Route path="about" element={<About />} /></Route></Routes></Router>);};export default App;
三、代码分割和懒加载
1. 懒加载原理和优势
1.1 优化初始加载性能
例如:将每个模块的组件懒加载,使得应用在初始启动时只加载必要的组件。
1.2 代码示例
import {BrowserRouter as Router,Route,Routes,lazy,Suspense,} from "react-router-dom";const Dashboard = lazy(() => import("./Dashboard"));const Reports = lazy(() => import("./Reports"));const Settings = lazy(() => import("./Settings"));const App = () => {return (<Router><Routes><Routepath="/dashboard"element={<Suspense fallback={<div>Loading...</div>}><Dashboard /></Suspense>}/><Routepath="/reports"element={<Suspense fallback={<div>Loading...</div>}><Reports /></Suspense>}/><Routepath="/settings"element={<Suspense fallback={<div>Loading...</div>}><Settings /></Suspense>}/></Routes></Router>);};export default App;