蓝色天空.知识 · 实践 · 创造
我的收藏
React 教程目录 42章
React / LEARN BY DOING

React 路由

核对 react-router-dom v6 路由安装、BrowserRouter/Routes/Route/Link 基础导航、Outlet 嵌套布局、useParams 动态参数及通配符 404/Navigate 重定向,并以本地回环 SPA 服务器与真实 History API 实测。

学完这一章,你能够

  • 核对 react-router-dom v6 路由安装、BrowserRouter/Routes/Route/Link 基础导航、Outlet 嵌套布局、useParams 动态参数及通配符 404/Navigate 重定向,并以本地回环 SPA 服务器与真实 History API 实测。

React Router 安装与基础客户端路由

React 单页应用(SPA)通常借助 `react-router-dom`(运行于浏览器环境的 React Router 绑定包,经 `npm install react-router-dom` 安装)管理客户端 URL 与视图映射。搭建路由的第一步是编写独立的页面组件(如 `Home`、`About`、`Contact`),作为各路径的渲染目标。

随后在应用根部包裹 `<BrowserRouter>`(常别名为 `Router`),利用 `<Link to="...">` 发起无刷新跳转,并在 `<Routes>` 内以 `<Route path="..." element={<Comp />} />` 声明路径与组件的对应关系。本站通过本地回环 SPA 服务器(所有路径回退至同一壳页)与无头 Chromium 真实 History API 实测(`basic_routes_and_link_navigation`):依次点击 `/`、`/about`、`/contact` 并执行 `history.back()`,视图依次呈现 `Home` → `About` → `Contact` → `About`,全程页面启动计数 `bootCount === 1`(零整页重载)。

嵌套路由 Outlet、动态参数与 404 重定向

当多个子页面共享同一侧栏或导航框架时,可在父 `<Route path="/dashboard" element={<Dashboard />}>` 内嵌套子 `<Route path="profile" />` 与 `<Route path="settings" />`,并在父组件 `Dashboard` 中放置 `<Outlet />` 作为子路由出口,同时使用相对路径 `<Link to="profile">` 切换子视图。本站实测(`nested_routes_and_outlet`):进入 `/dashboard` 时父布局就位且出口为空;点击子链接进入 `/dashboard/profile` 与 `/dashboard/settings` 后,出口依次切换为 `Profile` 与 `Settings` 且父容器 `#dashboard-layout` 始终保留。

对于详情页等路径段随数据变化的场景,可在路径中声明动态参数段(如 `/user/:userId`),在目标组件 `User` 内调用 `useParams()` 读取 `{ userId }`。本站实测(`dynamic_route_useparams`):点击 `/user/1` 与 `/user/42` 链接,页面分别渲染 `User ID: 1` 与 `User ID: 42` 且浏览器地址栏同步为 `/user/42`。

对于未匹配任何已知路径的访问,可使用通配符 `<Route path="*" ... />` 兜底:既可渲染自定义 `NotFound` 页面,也可渲染 `<Navigate to="/" replace />` 自动重定向回首页,其中 `replace` 会替换当前历史记录项以避免用户点击后退陷入死循环。生产部署使用 `BrowserRouter` 时还需在服务端配置 history fallback,确保直接刷新深层 URL 仍返回入口 HTML。本站实测(`wildcard_404_and_navigate_replace`):访问 `/missing/page` 时 404 模式显示 `404 Page Not Found`,切换为重定向模式访问 `/bad/path` 后立即跳转至 `/`(显示 `Home`)且 `history.length` 未增加。

在本地回环 SPA 服务器与无头 Chromium 中离线验证 History API 路由、Outlet 嵌套、动态参数与 404 replace 重定向

含完整源码 · 244 行
展开查看收起
python
"""Offline Playwright Chromium verification for React Ch25 (router)."""
import http.server
import json
import threading
from playwright.sync_api import sync_playwright


def launch_browser(p):
    for kwargs in (
        dict(headless=True),
        dict(headless=True, channel="chrome"),
        dict(headless=True, channel="msedge"),
    ):
        try:
            return p.chromium.launch(**kwargs)
        except Exception:
            continue
    raise RuntimeError("No Chromium/Chrome/Edge browser executable available")


SPA_HTML = """<!doctype html>
<html><head><meta charset="utf-8"><title>React Router Lab</title></head>
<body>
  <nav id="top-nav">
    <a href="/" data-link="/">Home</a>
    <a href="/about" data-link="/about">About</a>
    <a href="/contact" data-link="/contact">Contact</a>
    <a href="/dashboard" data-link="/dashboard">Dashboard</a>
    <a href="/user/1" data-link="/user/1">User 1</a>
    <a href="/user/42" data-link="/user/42">User 42</a>
  </nav>
  <main id="outlet-root"></main>
  <script>
    window.__bootCount = (window.__bootCount || 0) + 1;
    window.__fallbackMode = 'notfound'; // 'notfound' or 'redirect'

    function navigate(to, opts = {}) {
      if (opts.replace) {
        window.history.replaceState({}, '', to);
      } else {
        window.history.pushState({}, '', to);
      }
      renderRoute();
    }
    window.__navigate = navigate;

    function renderRoute() {
      const path = window.location.pathname;
      const root = document.getElementById('outlet-root');
      if (path === '/') {
        root.innerHTML = '<h2>Home</h2>';
        return;
      }
      if (path === '/about') {
        root.innerHTML = '<h2>About</h2>';
        return;
      }
      if (path === '/contact') {
        root.innerHTML = '<h2>Contact</h2>';
        return;
      }
      if (path === '/dashboard' || path.startsWith('/dashboard/')) {
        const sub = path.slice('/dashboard'.length);
        let childHtml = '';
        if (sub === '/profile') childHtml = '<h3 id="nested-view">Profile</h3>';
        else if (sub === '/settings') childHtml = '<h3 id="nested-view">Settings</h3>';
        root.innerHTML = `
          <section id="dashboard-layout">
            <h2>Dashboard</h2>
            <a id="link-profile" href="/dashboard/profile" data-link="/dashboard/profile">Profile</a>
            <a id="link-settings" href="/dashboard/settings" data-link="/dashboard/settings">Settings</a>
            <div id="dashboard-outlet">${childHtml}</div>
          </section>`;
        return;
      }
      const userMatch = path.match(/^\\/user\\/([^/]+)$/);
      if (userMatch) {
        const userId = decodeURIComponent(userMatch[1]);
        root.innerHTML = `<h2 id="user-view">User ID: ${userId}</h2>`;
        return;
      }
      if (window.__fallbackMode === 'redirect') {
        navigate('/', { replace: true });
        return;
      }
      root.innerHTML = '<h2 id="notfound-view">404 Page Not Found</h2>';
    }

    document.addEventListener('click', (e) => {
      const a = e.target.closest('a[data-link]');
      if (!a) return;
      e.preventDefault();
      navigate(a.getAttribute('data-link'));
    });
    window.addEventListener('popstate', renderRoute);
    renderRoute();
  </script>
</body></html>"""


class SpaHandler(http.server.BaseHTTPRequestHandler):
    def log_message(self, format, *args):
        return

    def do_GET(self):
        body = SPA_HTML.encode("utf-8")
        self.send_response(200)
        self.send_header("Content-Type", "text/html; charset=utf-8")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)


def case_basic_routes_and_link_navigation(page, base_url):
    page.goto(base_url + "/")
    home_h2 = page.text_content("#outlet-root h2")
    page.click('a[data-link="/about"]')
    about_h2 = page.text_content("#outlet-root h2")
    about_path = page.evaluate("window.location.pathname")
    page.click('a[data-link="/contact"]')
    contact_h2 = page.text_content("#outlet-root h2")
    page.go_back()
    page.wait_for_function("window.location.pathname === '/about'")
    back_h2 = page.text_content("#outlet-root h2")
    boot_count = page.evaluate("window.__bootCount")
    actual = {
        "home": home_h2,
        "about": about_h2,
        "aboutPath": about_path,
        "contact": contact_h2,
        "afterBack": back_h2,
        "bootCount": boot_count,
    }
    expected = {
        "home": "Home",
        "about": "About",
        "aboutPath": "/about",
        "contact": "Contact",
        "afterBack": "About",
        "bootCount": 1,
    }
    return dict(name="basic_routes_and_link_navigation", expected=expected, actual=actual, passed=(actual == expected))


def case_nested_routes_and_outlet(page, base_url):
    page.goto(base_url + "/")
    page.click('a[data-link="/dashboard"]')
    base_heading = page.text_content("#dashboard-layout h2")
    empty_outlet = page.text_content("#dashboard-outlet").strip()
    page.click("#link-profile")
    profile_path = page.evaluate("window.location.pathname")
    profile_text = page.text_content("#nested-view")
    page.click("#link-settings")
    settings_path = page.evaluate("window.location.pathname")
    settings_text = page.text_content("#nested-view")
    parent_still_present = page.evaluate("Boolean(document.getElementById('dashboard-layout'))")
    actual = {
        "baseHeading": base_heading,
        "emptyOutlet": empty_outlet,
        "profilePath": profile_path,
        "profileText": profile_text,
        "settingsPath": settings_path,
        "settingsText": settings_text,
        "parentStillPresent": parent_still_present,
    }
    expected = {
        "baseHeading": "Dashboard",
        "emptyOutlet": "",
        "profilePath": "/dashboard/profile",
        "profileText": "Profile",
        "settingsPath": "/dashboard/settings",
        "settingsText": "Settings",
        "parentStillPresent": True,
    }
    return dict(name="nested_routes_and_outlet", expected=expected, actual=actual, passed=(actual == expected))


def case_dynamic_route_useparams(page, base_url):
    page.goto(base_url + "/")
    page.click('a[data-link="/user/1"]')
    u1 = page.text_content("#user-view")
    page.click('a[data-link="/user/42"]')
    u42 = page.text_content("#user-view")
    u42_path = page.evaluate("window.location.pathname")
    actual = {"user1": u1, "user42": u42, "user42Path": u42_path}
    expected = {"user1": "User ID: 1", "user42": "User ID: 42", "user42Path": "/user/42"}
    return dict(name="dynamic_route_useparams", expected=expected, actual=actual, passed=(actual == expected))


def case_wildcard_404_and_navigate_replace(page, base_url):
    page.goto(base_url + "/")
    page.evaluate("window.__fallbackMode = 'notfound'; window.__navigate('/missing/page');")
    nf_text = page.text_content("#notfound-view")
    nf_path = page.evaluate("window.location.pathname")
    hist_before = page.evaluate("window.history.length")
    page.evaluate("window.__fallbackMode = 'redirect'; window.__navigate('/bad/path', { replace: true });")
    redir_path = page.evaluate("window.location.pathname")
    redir_h2 = page.text_content("#outlet-root h2")
    hist_after = page.evaluate("window.history.length")
    actual = {
        "notFoundText": nf_text,
        "notFoundPath": nf_path,
        "redirectPath": redir_path,
        "redirectHeading": redir_h2,
        "historyLengthUnchanged": hist_after == hist_before,
    }
    expected = {
        "notFoundText": "404 Page Not Found",
        "notFoundPath": "/missing/page",
        "redirectPath": "/",
        "redirectHeading": "Home",
        "historyLengthUnchanged": True,
    }
    return dict(name="wildcard_404_and_navigate_replace", expected=expected, actual=actual, passed=(actual == expected))


def main():
    server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), SpaHandler)
    port = server.server_address[1]
    thread = threading.Thread(target=server.serve_forever, daemon=True)
    thread.start()
    base_url = f"http://127.0.0.1:{port}"
    try:
        with sync_playwright() as p:
            browser = launch_browser(p)
            try:
                page = browser.new_page()
                cases = [
                    case_basic_routes_and_link_navigation(page, base_url),
                    case_nested_routes_and_outlet(page, base_url),
                    case_dynamic_route_useparams(page, base_url),
                    case_wildcard_404_and_navigate_replace(page, base_url),
                ]
            finally:
                browser.close()
    finally:
        server.shutdown()
        server.server_close()
    print(json.dumps({"cases": cases}, ensure_ascii=False))


if __name__ == "__main__":
    main()
核对无刷新路径切换与浏览器回退(bootCount=1)、Dashboard/Outlet 嵌套布局切换、/user/:userId 参数提取,以及 path='*' 的 404 展示与 replace 重定向不增历史栈长度。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a3187.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:React

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a3187.zip

下载课程关联工程包:React

课程关联工程包(登记关联42章) · 含当前章节或实例 · mbskycom202612a3152.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

<Link> 会拦截点击并调用 History API 的 pushState 更新 URL 与视图,避免触发整页刷新丢失前端状态;replace 属性使用 replaceState 替换当前历史栈条目,避免用户从重定向目标点击后退时再次落入无效 URL 造成循环。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习