React Routerrouting

LearningReact Routerroutingmanagement, includingroutingconfiguration, 嵌套routing, routingparameter, 导航, 守卫etc. in 容

1. React RouterIntroduction

React Router is React官方推荐 routinglibrary, 用于构建单页application (SPA) routingsystem. 它允许我们 in Reactapplicationinimplementation页面之间 导航, 而无需刷 new 整个页面.

1.1 installationReact Router

// installationReact Router v6
npm install react-router-dom@6

2. basicroutingconfiguration

React Router v6usingcomponent化 方式configurationrouting.

// import必要 component
import { BrowserRouter, Routes, Route, Link } from 'react-router-dom';

// 页面component
function Home() {
  return <h2>首页</h2>;
}

function About() {
  return <h2>About Us</h2>;
}

function Contact() {
  return <h2>Contact Us</h2>;
}

// Appcomponent
function App() {
  return (
    <BrowserRouter>
      <div>
        <nav>
          <ul>
            <li>
              <Link to="/">首页</Link>
            </li>
            <li>
              <Link to="/about">About Us</Link>
            </li>
            <li>
              <Link to="/contact">Contact Us</Link>
            </li>
          </ul>
        </nav>

        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/about" element={<About />} />
          <Route path="/contact" element={<Contact />} />
        </Routes>
      </div>
    </BrowserRouter>
  );
}

提示

in React Router v6in, <Switch>component被<Routes>component替代, <Route>component 语法也 has 所变化.

3. 嵌套routing

嵌套routing允许我们 in 父routingin嵌套子routing, implementation更 complex routingstructure.

import { BrowserRouter, Routes, Route, Link, Outlet } from 'react-router-dom';

// 父component
function Dashboard() {
  return (
    <div>
      <h2>仪表板</h2>
      <nav>
        <ul>
          <li>
            <Link to="/dashboard">概览</Link>
          </li>
          <li>
            <Link to="/dashboard/settings">设置</Link>
          </li>
          <li>
            <Link to="/dashboard/profile">个人资料</Link>
          </li>
        </ul>
      </nav>
      <Outlet /> {/* 渲染子routingcomponent */}
    </div>
  );
}

// 子component
function Overview() {
  return <h3>概览</h3>;
}

function Settings() {
  return <h3>设置</h3>;
}

function Profile() {
  return <h3>个人资料</h3>;
}

// Appcomponent
function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/dashboard" element={<Dashboard />}>
          <Route index element={<Overview />} /> {/* 默认子routing */}
          <Route path="settings" element={<Settings />} />
          <Route path="profile" element={<Profile />} />
        </Route>
      </Routes>
    </BrowserRouter>
  );
}

4. routingparameter

routingparameter允许我们 in URLin传递动态data.

import { BrowserRouter, Routes, Route, Link, useParams } from 'react-router-dom';

// 产品listcomponent
function ProductList() {
  const products = [
    { id: 1, name: '产品1' },
    { id: 2, name: '产品2' },
    { id: 3, name: '产品3' }
  ];
  
  return (
    <div>
      <h2>产品list</h2>
      <ul>
        {products.map(product => (
          <li key={product.id}>
            <Link to={`/products/${product.id}`}>{product.name}</Link>
          </li>
        ))}
      </ul>
    </div>
  );
}

// 产品详情component
function ProductDetail() {
  const { id } = useParams(); // 获取routingparameter
  
  return (
    <div>
      <h2>产品详情</h2>
      <p>产品ID: {id}</p>
    </div>
  );
}

// Appcomponent
function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/products" element={<ProductList />} />
        <Route path="/products/:id" element={<ProductDetail />} />
      </Routes>
    </BrowserRouter>
  );
}

5. programming式导航

除了using<Link>componentfor声明式导航 out , 我们还可以usinguseNavigate Hookforprogramming式导航.

import { BrowserRouter, Routes, Route, useNavigate } from 'react-router-dom';

function Home() {
  const navigate = useNavigate();
  
  const handleClick = () => {
    navigate('/about'); // 导航 to /about
  };
  
  const handleGoBack = () => {
    navigate(-1); // 返回 on 一页
  };
  
  const handleGoForward = () => {
    navigate(1); //  before 进 to  under 一页
  };
  
  const handleReplace = () => {
    navigate('/contact', { replace: true }); // replace当 before 页面, 不会添加 to history记录
  };
  
  return (
    <div>
      <h2>首页</h2>
      <button onClick={handleClick}>跳转 to About Us</button>
      <button onClick={handleGoBack}>返回 on 一页</button>
      <button onClick={handleGoForward}> before 进 to  under 一页</button>
      <button onClick={handleReplace}>replace to Contact Us</button>
    </div>
  );
}

function About() {
  return <h2>About Us</h2>;
}

function Contact() {
  return <h2>Contact Us</h2>;
}

function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
        <Route path="/contact" element={<Contact />} />
      </Routes>
    </BrowserRouter>
  );
}

6. routing守卫

routing守卫用于控制routing 访问permission, 例such asverificationuser is 否login.

import { BrowserRouter, Routes, Route, Navigate, Outlet } from 'react-router-dom';

// mockloginstatus
const isAuthenticated = true;

// 受保护 routingcomponent
function ProtectedRoute() {
  if (!isAuthenticated) {
    return <Navigate to="/login" replace />; // 未login则跳转 to login页
  }
  
  return <Outlet />; // 已login则渲染子routingcomponent
}

// logincomponent
function Login() {
  return <h2>login页面</h2>;
}

// 仪表板component
function Dashboard() {
  return <h2>仪表板 (需要login) </h2>;
}

// Appcomponent
function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/login" element={<Login />} />
        <Route element={<ProtectedRoute />}>
          <Route path="/dashboard" element={<Dashboard />} />
        </Route>
      </Routes>
    </BrowserRouter>
  );
}

7. 404页面

当user访问不存 in routing时, 我们可以显示一个404页面.

import { BrowserRouter, Routes, Route, Link } from 'react-router-dom';

// 404页面component
function NotFound() {
  return (
    <div>
      <h2>404 - 页面未找 to </h2>
      <p>您访问 页面不存 in . </p>
      <Link to="/">返回首页</Link>
    </div>
  );
}

// other页面component...

// Appcomponent
function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
        <Route path="/contact" element={<Contact />} />
        <Route path="*" element={<NotFound />} /> {/* 404routing, 放 in 最 after  */}
      </Routes>
    </BrowserRouter>
  );
}

练习 1: basicroutingconfiguration

  1. creation一个Reactapplication, installationReact Router
  2. configuration首页, 关于页面, 联系页面 routing
  3. 添加导航链接, implementation页面之间 跳转

练习 2: 嵌套routing and routingparameter

  1. creation一个博客application, configuration嵌套routing
  2. implementation博客list and 博客详情页面
  3. usingroutingparameter传递博客ID