1. 基本概念
React?Router 是 React 的路由管理庫,用于在 React 應用中實現頁面導航和路由控制。
2. 安裝
npm install react-router-dom
3. 基礎用法
// App.jsx
import { BrowserRouter, Routes, Route, Link } from 'react-router-dom'function App() {return (<BrowserRouter>{/* 導航鏈接 */}<nav><Link to="/">首頁</Link><Link to="/about">關于</Link><Link to="/user">用戶</Link></nav>{/* 路由配置 */}<Routes><Route path="/" element={<Home />} /><Route path="/about" element={<About />} /><Route path="/user" element={<User />} /></Routes></BrowserRouter>)
}
4. 路由類型
1.?BrowserRouter:使用 HTML5 history API
<BrowserRouter>{/* 你的應用 */}
</BrowserRouter>
2.HashRouter:使用?URL 的 hash 部分
<HashRouter>{/* 你的應用 */}
</HashRouter>
5. 路由導航
1.聲明式導航(Link組件):
<Link to="/about">關于我們</Link>
<Link to="/user/123">用戶詳情</Link>
2.編程式導航(useNavigate鉤子) :
import { useNavigate } from 'react-router-dom'function LoginButton() {const navigate = useNavigate()const handleLogin = () => {// 登錄成功后跳轉navigate('/dashboard')// 帶參數跳轉navigate('/user', { state: { id: 123 } })// 返回上一頁navigate(-1)}return <button onClick={handleLogin}>登錄</button>
}
6. 路由參數
1.?URL參數:
// 路由配置
<Route path="/user/:id" element={<UserDetail />} />// 組件中獲取參數
import { useParams } from 'react-router-dom'function UserDetail() {const { id } = useParams()return <div>用戶ID:{id}</div>
}
2. 查詢參數:
// 使用查詢參數
<Link to="/search?keyword=react">搜索</Link>// 獲取查詢參數
import { useSearchParams } from 'react-router-dom'function Search() {const [searchParams] = useSearchParams()const keyword = searchParams.get('keyword')return <div>搜索關鍵詞:{keyword}</div>
}
7. 嵌套路由
function App() {return (<Routes><Route path="/" element={<Layout />}><Route index element={<Home />} /><Route path="about" element={<About />} /><Route path="users" element={<Users />}><Route path=":id" element={<UserDetail />} /></Route></Route></Routes>)
}// Layout組件
function Layout() {return (<div><nav>{/* 導航欄 */}</nav><Outlet /> {/* 子路由渲染位置 */}</div>)
}
8. 路由守衛(保護路由)
function PrivateRoute({ children }) {const isAuthenticated = checkAuth() // 檢查用戶是否登錄if (!isAuthenticated) {return <Navigate to="/login" replace />}return children
}// 使用
<Route path="/dashboard" element={<PrivateRoute><Dashboard /></PrivateRoute>}
/>
9. 路由鉤子
// 1. useLocation - 獲取當前路由信息
function Component() {const location = useLocation()console.log(location.pathname) // 當前路徑console.log(location.search) // 查詢參數console.log(location.state) // 路由狀態
}// 2. useNavigate - 編程式導航
function Component() {const navigate = useNavigate()navigate('/path')
}// 3. useParams - 獲取URL參數
function Component() {const { id } = useParams()
}// 4. useSearchParams - 獲取查詢參數
function Component() {const [searchParams, setSearchParams] = useSearchParams()
}
10. 實際應用示例
// 完整的路由配置示例
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom'function App() {return (<BrowserRouter><Routes>{/* 公共路由 */}<Route path="/" element={<Layout />}><Route index element={<Home />} /><Route path="about" element={<About />} /><Route path="products" element={<Products />}><Route path=":id" element={<ProductDetail />} /></Route>{/* 需要認證的路由 */}<Route path="dashboard" element={<PrivateRoute><Dashboard /></PrivateRoute>}><Route path="profile" element={<Profile />} /><Route path="settings" element={<Settings />} /></Route>{/* 404頁面 */}<Route path="*" element={<NotFound />} />{/* 重定向 */}<Route path="old-path" element={<Navigate to="/new-path" replace />} /></Route></Routes></BrowserRouter>)
}
11. 最佳實踐
1.路由配置集中管理:
// routes.js
const routes = [{path: '/',element: <Layout />,children: [{ index: true, element: <Home /> },{ path: 'about', element: <About /> },{ path: 'users', element: <Users /> }]}
]// App.jsx
import { useRoutes } from 'react-router-dom'function App() {const element = useRoutes(routes)return element
}
2.懶加載路由:
import { lazy, Suspense } from 'react'const Dashboard = lazy(() => import('./pages/Dashboard'))function App() {return (<Routes><Route path="/dashboard" element={<Suspense fallback={<Loading />}><Dashboard /></Suspense>} /></Routes>)
}
這些內容涵蓋了?React Router 的主要使用方法。記住:
- 總是在應用最外層包裹?BrowserRouter
- 使用?Routes?和?Route?定義路由規則
- 使用?Link?或?useNavigate?進行導航
- 合理使用路由鉤子獲取和操作路由信息
- 需要時使用路由守衛保護私有路由
- 考慮使用懶加載優化性能