React Router 是一個用於在 React 應用程式中處理路由的函式庫。它允許您的應用程式在不同的元件和視圖之間導航,而無需重新載入整頁,從而實現無縫的用戶體驗。
先安裝react-router-dom:
npm install react-router-dom
使用 BrowserRouter、Routes 和 Route 設定基本路由:
import React from 'react'; import { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom'; const Home = () =>Home
; const About = () =>About
; const App = () => { return (); }; export default App; } /> } />
對於更複雜的應用程序,您可以嵌套路由。以下是如何在父元件中設定嵌套路由:
import React from 'react'; import { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom'; const Dashboard = () =>Dashboard Home
; const Profile = () =>Your Profile
; const DashboardLayout = () => { return (); }; const App = () => { return (} /> } /> ); }; export default App; } />
動態路由可讓您在 URL 中傳遞參數。以下是定義和存取動態路由的方法:
import { useParams } from 'react-router-dom'; const User = () => { const { id } = useParams(); returnUser ID: {id}
; }; const App = () => { return (); }; export default App; } />
要實現受保護的路由,您可以建立自訂 PrivateRoute 元件:
import { Navigate, Outlet } from 'react-router-dom'; const useAuth = () => { const user = { loggedIn: true }; // Replace with actual auth logic return user && user.loggedIn; }; const PrivateRoute = () => { const isAuth = useAuth(); return isAuth ?: ; }; const App = () => { return ( ); }; export default App; } /> }> } />
有時,您可能希望以程式設計方式導航,例如在提交表單後。在 React Router v6 中使用 useNavigate 鉤子:
import { useNavigate } from 'react-router-dom'; const Login = () => { const navigate = useNavigate(); const handleLogin = () => { // Login logic here... navigate('/dashboard'); }; return (); }; export default Login;Login
透過建立包羅萬象的路由來處理 404(未找到)錯誤:
const NotFound = () =>404 - Page Not Found
; const App = () => { return (); }; export default App; } /> } /> } />
對於大型應用程序,延遲載入路由可以提高效能。以下是如何使用 React.lazy() 和 Suspense 實作延遲載入:
import React, { Suspense, lazy } from 'react'; import { BrowserRouter as Router, Routes, Route } from 'react-router-dom'; const Home = lazy(() => import('./Home')); const About = lazy(() => import('./About')); const App = () => { return (); }; export default App; Loading...}> } /> } />
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3