蓝色天空网mbsky.com · 知识 · 实践 · 创造React · 本地阅读预览
教程 / 前端开发 / React

路由跳转

核对前端 SPA 路由原理、React Router v6 路由表与 Browser/Hash 模式、RouterProvider 与 Outlet 嵌套出口、Link 无刷新跳转、useParams 字符串转换、useNavigate 编程式跳转及文章详情页实战。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

前端路由原理与 React Router v6 核心配置

传统多页网站每次点击超链接都需要向服务器请求整页 HTML,易出现白屏闪烁;前端路由拦截 URL 变化并由 JavaScript 在客户端切换视图组件,实现无刷新流畅跳转。React Router v6 的核心由五项概念组成:定义路径与组件映射的路由表(`<Routes>` + `<Route>` 或对象配置)、渲染匹配子路由的出口 `<Outlet />`、声明式导航 `<Link to="...">`、含路径变量的动态路由 `/post/:id`,以及读取参数的 `useParams()`。

执行 `npm install react-router-dom@6` 后,可在 `src/router/index.jsx` 中使用 `createBrowserRouter` 定义根布局 `path: '/'`(渲染 `<App />`)及其子路由 `index: true`(默认首页 `<HomePage />`)与动态详情页 `path: 'post/:id'`(`<PostPage />`)。两种历史模式各有适用边界:`createBrowserRouter` 生成干净路径 `/post/1` 但上线需服务器配置 SPA 回退;`createHashRouter` 生成带 `#` 的路径 `/#/post/1` 且无需服务器改写。入口 `src/main.jsx` 通过 `<RouterProvider router={router} />` 注入路由,`src/App.jsx` 保留 `<NavBar />` 与页脚并在 `<main>` 内放置 `<Outlet />` 承载子页面。

Link 无刷新导航、useParams 与 useNavigate

页面内部跳转应使用 `<Link to={`/post/${id}`}>` 替代原生 `<a href="...">`:原生超链接会触发整页 HTTP 请求导致 React 应用重新初始化,而 `<Link>` 基于 History API 局部替换 `<Outlet />`。本站离线 Chromium 在本地回环服务器实测点击首篇文章卡片跳转到 `/post/1`:文档启动标识 `BOOT-REACT-ROUTER-36` 全程未变(零整页刷新),`<NavBar />` 持续保留,详情标题切换为 `React 入门完全指南`;切至 Hash 路径 `#/post/2` 同样无刷新渲染 `JS 异步编程详解`。

在详情页中通过 `const { id } = useParams()` 获取动态路径参数,注意返回值始终为字符串类型,与数字型文章 ID 匹配前需用 `Number(id)` 显式转换。若需在表单提交或查无文章时通过代码触发跳转,则调用 `const navigate = useNavigate()` 并执行 `navigate('/')`。本站实测访问 `/post/1` 读取到的 `id` 为 `'1'`(`typeof === 'string'`),转换为数字 `1` 后精确命中正文;访问 `/post/999` 渲染 `文章不存在` 与 `找不到 ID 为 999 的文章`,点击编程式返回按钮后无刷新回到 `/` 并恢复 3 张卡片;浏览器后退(`popstate`)也能正确从 `/post/3` 返回首页。

详情页整合、dangerouslySetInnerHTML 安全边界与样式

实战改造分三步完成:用 `<Link to={`/post/${id}`}>` 包裹 `BlogCard`;拆分 `HomePage.jsx`(保留分类筛选与文章卡片网格)与 `PostPage.jsx`(按 `Number(id)` 查找文章、处理不存在回退,并在文章正文容器使用 `dangerouslySetInnerHTML={{ __html: article.content }}` 渲染受信任的开发者 HTML 内容——该 API 故意命名冗长以警示绝不可直接渲染未净化用户输入,避免 XSS 风险);最后追加 `.post-view`(`max-width: 720px`)等详情排版样式。本站实测确认详情正文小标题 `为什么学 React?` 与 `.post-view` 计算最大宽度 `720px` 均准确生效。

React Router v6 五大核心概念速查

核心概念主要职责对应语法
路由映射表声明 URL 路径与目标页面组件的对应关系<Routes> + <Route>
嵌套子路由出口在父级布局组件中标明子路由渲染占位区域<Outlet />
声明式导航链接拦截默认整页跳转,在客户端无刷新切换 URL<Link to="...">
动态路径段用冒号占位匹配不同文章 ID 等可变路径/post/:id
参数提取 Hook在目标页面组件中读取当前动态路径参数对象useParams()

Vue Router 4 与 React Router v6 常用 API 对照

路由能力Vue 3 生态React 生态
声明式跳转组件<RouterLink><Link>
子视图占位出口<RouterView><Outlet>
参数化路径模板/post/:id/post/:id
获取动态参数useRoute().paramsuseParams()
脚本触发路由跳转useRouter().push()useNavigate()

离线 Chromium 实测本地回环 SPA History/Hash 路由、Link 无刷新跳转、useParams 与 useNavigate

python · 阅读源码
"""Offline Playwright Chromium lab for React Ch 36: Client-side Router, Outlet, Link, useParams & useNavigate."""
import json
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from playwright.sync_api import sync_playwright


def launch_browser(p):
    try:
        return p.chromium.launch(headless=True)
    except Exception:
        return p.chromium.launch(headless=True, channel="chrome")


HTML = r"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>React Router v6 Offline Lab</title>
<style>
.post-view { max-width: 720px; margin: 0 auto; }
.category-tag { display: inline-block; padding: 4px 12px; background: #e3f2fd; color: #1976d2; border-radius: 12px; }
.not-found { text-align: center; padding: 40px 0; }
.card-link { display: block; border: 1px solid #ddd; padding: 10px; margin: 8px 0; text-decoration: none; color: #222; }
</style>
</head>
<body>
  <div id="root"></div>
<script>
window.__SPA_BOOT_ID = "BOOT-REACT-ROUTER-36";
window.__LAST_PARAMS = null;

const ARTICLES = [
  { id: 1, title: "React 入门完全指南", summary: "从零学 React", category: "React", date: "2024-05-10",
    content: "<h2>为什么学 React?</h2><p>组件化与声明式 UI 是现代前端基石。</p>" },
  { id: 2, title: "JS 异步编程详解", summary: "搞懂 Promise 和 async/await", category: "JavaScript", date: "2024-05-08",
    content: "<h2>什么是异步?</h2><p>事件循环与微任务让主线程保持响应。</p>" },
  { id: 3, title: "CSS Grid 布局实战", summary: "用 Grid 实现响应式布局", category: "CSS", date: "2024-05-05",
    content: "<h2>Grid 入门</h2><p>二维网格系统简化复杂排版。</p>" }
];

// Route matching for BrowserRouter & HashRouter patterns
function matchRoute(pathname) {
  if (pathname === "/" || pathname === "") return { route: "home", params: {} };
  const m = pathname.match(/^\/post\/([^/]+)$/);
  if (m) return { route: "post", params: { id: m[1] } };
  return { route: "404", params: {} };
}

function navigate(to) {
  window.history.pushState({}, "", to);
  renderRouter();
}

function createLink(to, className, contentNodeOrHtml) {
  const a = document.createElement("a");
  a.href = to;
  if (className) a.className = className;
  if (typeof contentNodeOrHtml === "string") a.innerHTML = contentNodeOrHtml;
  else a.appendChild(contentNodeOrHtml);
  a.addEventListener("click", (e) => {
    e.preventDefault();
    navigate(to);
  });
  return a;
}

function renderHomePage() {
  const wrap = document.createElement("div");
  wrap.id = "home-page";
  wrap.innerHTML = `<h2 class="section-title">最新文章</h2>`;
  const grid = document.createElement("div");
  grid.className = "article-grid";
  ARTICLES.forEach((a) => {
    const card = createLink(`/post/${a.id}`, "card-link",
      `<div class="card" data-id="${a.id}"><span class="tag">${a.category}</span><h3>${a.title}</h3><p>${a.summary}</p></div>`);
    grid.appendChild(card);
  });
  wrap.appendChild(grid);
  return wrap;
}

function renderPostPage(params) {
  // useParams() returns string parameters
  window.__LAST_PARAMS = { rawId: params.id, typeofId: typeof params.id, numericId: Number(params.id) };
  const article = ARTICLES.find((a) => a.id === Number(params.id));
  if (!article) {
    const nf = document.createElement("div");
    nf.className = "not-found";
    nf.innerHTML = `<h2>文章不存在</h2><p>找不到 ID 为 ${params.id} 的文章</p>`;
    const backBtn = document.createElement("button");
    backBtn.id = "btn-nav-home";
    backBtn.textContent = "编程式返回首页";
    backBtn.addEventListener("click", () => navigate("/"));
    nf.appendChild(backBtn);
    return nf;
  }
  const art = document.createElement("article");
  art.className = "post-view";
  art.innerHTML = `
    <span class="category-tag">${article.category}</span>
    <h1>${article.title}</h1>
    <time>${article.date}</time>
    <div class="content">${article.content}</div>`;
  art.appendChild(createLink("/", "back-link", "← 返回首页"));
  return art;
}

function renderRouter() {
  const effectivePath = window.location.hash.startsWith("#/")
    ? window.location.hash.slice(1)
    : window.location.pathname;
  const matched = matchRoute(effectivePath);
  const root = document.getElementById("root");
  // Preserve outer layout shell (App + NavBar + Outlet)
  if (!document.getElementById("outlet")) {
    root.innerHTML = `<div class="app"><header class="navbar"><span class="logo">BlueSky Blog</span></header><main id="outlet" class="container"></main><footer class="footer">© 2026 BlueSky Blog</footer></div>`;
  }
  const outlet = document.getElementById("outlet");
  if (matched.route === "home") outlet.replaceChildren(renderHomePage());
  else if (matched.route === "post") outlet.replaceChildren(renderPostPage(matched.params));
  else {
    const nf = document.createElement("div");
    nf.className = "not-found";
    nf.innerHTML = `<h2>404 页面不存在</h2>`;
    outlet.replaceChildren(nf);
  }
}

window.addEventListener("popstate", renderRouter);
window.addEventListener("hashchange", renderRouter);
window.navTo = navigate;
renderRouter();
</script>
</body>
</html>
"""


class SpaHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        body = 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 log_message(self, format, *args):
        return


def main():
    server = ThreadingHTTPServer(("127.0.0.1", 0), SpaHandler)
    port = server.server_address[1]
    thread = threading.Thread(target=server.serve_forever, daemon=True)
    thread.start()

    cases = []
    try:
        with sync_playwright() as p:
            browser = launch_browser(p)
            page = browser.new_page()
            base = f"http://127.0.0.1:{port}"
            page.goto(base + "/")

            # Case 1: Link navigation + Outlet swap without page reload + Hash fallback
            boot_before = page.evaluate("() => window.__SPA_BOOT_ID")
            page.locator('.card-link[href="/post/1"]').click()
            url_after_click = page.evaluate("() => window.location.pathname")
            boot_after = page.evaluate("() => window.__SPA_BOOT_ID")
            post_title = page.locator(".post-view h1").inner_text()
            navbar_persisted = page.locator(".navbar .logo").inner_text()

            # Test hash router path resolution without reload
            page.evaluate("() => { window.location.hash = '#/post/2'; }")
            hash_title = page.locator(".post-view h1").inner_text()
            page.evaluate("() => { window.location.hash = ''; window.navTo('/post/1'); }")

            c1_actual = {
                "url_after_click": url_after_click,
                "same_document": boot_before == boot_after,
                "post_title": post_title,
                "navbar_persisted": navbar_persisted,
                "hash_title": hash_title,
            }
            c1_expected = {
                "url_after_click": "/post/1",
                "same_document": True,
                "post_title": "React 入门完全指南",
                "navbar_persisted": "BlueSky Blog",
                "hash_title": "JS 异步编程详解",
            }
            cases.append({
                "name": "spa_history_link_and_outlet",
                "expected": c1_expected,
                "actual": c1_actual,
                "passed": c1_actual == c1_expected,
            })

            # Case 2: useParams string type & Number(id) lookup + HTML content render
            params_info = page.evaluate("() => window.__LAST_PARAMS")
            content_h2 = page.locator(".post-view .content h2").inner_text()
            post_max_w = page.locator(".post-view").evaluate("el => getComputedStyle(el).maxWidth")
            c2_actual = {
                "rawId": params_info["rawId"],
                "typeofId": params_info["typeofId"],
                "numericId": params_info["numericId"],
                "content_h2": content_h2,
                "post_max_w": post_max_w,
            }
            c2_expected = {
                "rawId": "1",
                "typeofId": "string",
                "numericId": 1,
                "content_h2": "为什么学 React?",
                "post_max_w": "720px",
            }
            cases.append({
                "name": "useparams_string_to_number",
                "expected": c2_expected,
                "actual": c2_actual,
                "passed": c2_actual == c2_expected,
            })

            # Case 3: Missing article 404 branch & useNavigate programmatic redirect
            page.evaluate("() => window.navTo('/post/999')")
            nf_heading = page.locator(".not-found h2").inner_text()
            nf_msg = page.locator(".not-found p").inner_text()
            page.locator("#btn-nav-home").click()
            back_path = page.evaluate("() => window.location.pathname")
            home_cards = page.locator("#home-page .card").count()
            c3_actual = {
                "nf_heading": nf_heading,
                "nf_msg": nf_msg,
                "back_path": back_path,
                "home_cards": home_cards,
                "still_same_doc": page.evaluate("() => window.__SPA_BOOT_ID") == boot_before,
            }
            c3_expected = {
                "nf_heading": "文章不存在",
                "nf_msg": "找不到 ID 为 999 的文章",
                "back_path": "/",
                "home_cards": 3,
                "still_same_doc": True,
            }
            cases.append({
                "name": "not_found_and_usenavigate",
                "expected": c3_expected,
                "actual": c3_actual,
                "passed": c3_actual == c3_expected,
            })

            # Case 4: Back link & browser history popstate navigation
            page.locator('.card-link[href="/post/3"]').click()
            p3_title = page.locator(".post-view h1").inner_text()
            page.go_back()
            restored_path = page.evaluate("() => window.location.pathname")
            restored_section = page.locator("#home-page .section-title").inner_text()
            c4_actual = {
                "p3_title": p3_title,
                "restored_path": restored_path,
                "restored_section": restored_section,
            }
            c4_expected = {
                "p3_title": "CSS Grid 布局实战",
                "restored_path": "/",
                "restored_section": "最新文章",
            }
            cases.append({
                "name": "browser_back_popstate_navigation",
                "expected": c4_expected,
                "actual": c4_actual,
                "passed": c4_actual == c4_expected,
            })

            browser.close()
    finally:
        server.shutdown()
        server.server_close()

    print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 核对点击卡片跳转 /post/1 不重载页面(BOOT-REACT-ROUTER-36 不变)、Hash 路径切换、useParams 返回字符串 '1'、/post/999 404 回退及浏览器 popstate 后退。
离线 Chromium 实测本地回环 SPA History/Hash 路由、Link 无刷新跳转、useParams 与 useNavigate

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

当前源码 SHA256:1a2660ea84128d4c827175312e5b6d16282af085c331f10a0bbb79f33abc5f8a

下载本站示例源码

本地运行

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

下载路由跳转实验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

ZIP SHA256:7f437f7331f86611a200319bfbb4db1451d0308e10dadffb023e2854ab1cfab3

常见错误与边界

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

练习与解答

在详情页中 `useParams()` 解构出的 `id` 为什么不能直接用 `===` 与数字型文章 ID 比对?`createBrowserRouter` 与 `createHashRouter` 部署时有何差异?

展开参考解答

URL 路径参数经 `useParams()` 解析后永远是字符串(如 `'1'`),与数字 `1` 严格相等比较会返回 `false`,必须先用 `Number(id)` 转换。`createBrowserRouter` 使用干净路径,线上需配置服务器将未知子路径回退到 `index.html`;`createHashRouter` 依赖 `#` 片段,无需额外服务端重写。

规范与官方依据