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

全局状态

核对 Prop Drilling 痛点与 Context 三步用法、useReducer 纯函数分发与 useState 选用对比、Context + useReducer 组合实现跨组件收藏同步与 localStorage 持久化,以及与 Vue 3 Pinia 对照。

学完这一章,你能够

  • 核对 Prop Drilling 痛点与 Context 三步用法、useReducer 纯函数分发与 useState 选用对比、Context + useReducer 组合实现跨组件收藏同步与 localStorage 持久化,以及与 Vue 3 Pinia 对照。

全局状态痛点与 Context 核心机制

收藏列表、登录身份与购物车数据往往需要被首页、详情页、导航栏等互不相邻的组件共同访问。若继续沿着组件树 `A → B → C → D` 逐层透传 Props,就会产生繁琐的 Props 逐层传递(Prop Drilling),迫使中间层组件被动接收并不使用的属性。React 内置的 Context 提供跨层级数据通道,分三步运作:`createContext()` 创建容器、顶层 `<Provider value={...}>` 广播数据、任意后代调用 `useContext(MyContext)` 直接订阅。本站离线 Chromium 实测 `ThemeContext` 跨越三层中间容器将主题传至底层 `ThemedButton`,点击后标签直接从 `当前主题:light` 切换为 `当前主题:dark`,且在 `FavoriteProvider` 外部调用 `useFavorites()` 会立即抛出明确守卫错误 `useFavorites 必须在 FavoriteProvider 内部使用`。

useReducer 管理复杂状态与 useState 对比

当状态包含多项关联更新或多种操作类型(如收藏的切换 `TOGGLE`、清空 `CLEAR`)时,用 `useReducer(reducer, initialState)` 将所有状态迁移集中到纯函数 `(state, action) => nextState` 中,并通过 `dispatch({ type, ... })` 触发,可让更新路径清晰可控且易于调试。本站离线 Chromium 实测 `favoriteReducer` 迁移链路:初始 `[]` 依次执行 `TOGGLE(1)` 得 `[1]`、`TOGGLE(2)` 得 `[1, 2]`、`TOGGLE(1)` 取消得 `[2]`、未知 action `NOOP` 原样返回同一引用、执行 `CLEAR` 归零为 `[]`。

Context + useReducer 组合模式与博客收藏实战

将 `Context` 与 `useReducer` 组合在 `src/context/FavoriteContext.jsx` 中是 React 内置的轻量级全局状态方案:`FavoriteProvider` 利用 `useReducer` 第三个惰性初始化参数从 `localStorage('blog-favorites')` 恢复已存收藏,通过 `useEffect(..., [favoriteIds])` 在收藏变化时自动同步回写 `localStorage`,并通过自定义 Hook `useFavorites()` 封装 `useContext` 与空值报错校验。在 `src/main.jsx` 中必须将 `<FavoriteProvider>` 包裹在 `<RouterProvider router={router} />` 外层,这样位于根布局 `App` 内的 `NavBar` 与各路由页面都能访问同一份收藏状态。

接入三处消费组件后:`BlogCard` 收藏按钮需调用 `e.preventDefault()` 阻止外层 `<Link>` 触发跳转;`PostPage` 显示当前文章收藏态并支持切换;`NavBar` 实时展示 `favoriteCount > 0` 时的角标数量。本站离线 Chromium 在本地回环源下实测跨组件联动与刷新持久化:初始导航栏无角标;在首页卡片 #1 点击收藏后路由仍停留在 `/`、心形变为 `♥`、导航栏同步出现 `收藏 1`;进入文章 #1 详情页自动显示 `♥ 已收藏`,在详情页取消收藏后按钮变为 `♡ 收藏` 且导航栏角标自动隐藏;返回首页连续收藏 #1 与 #3 后 `localStorage('blog-favorites')` 写入 `[1,3]`,整页 `page.reload()` 刷新后导航栏立即恢复 `收藏 2` 且三张卡片心形状态准确还原为 `['♥', '♡', '♥']`。

React Context 三步工作流速查

实施步骤核心代码职责说明
1. 创建容器createContext()创建跨层级共享数据的 Context 对象
2. 顶层注入<Provider value={...}>在组件树外层包裹并向下广播状态与操作方法
3. 后代读取useContext(MyContext)在任意深度子孙组件中直接读取上下文数据

useState 与 useReducer 典型场景选用指南

状态场景推荐 Hook选用理由
单个简单独立状态useState声明与更新语法最直接,心智负担小
多字段联动更新useReducer单次 dispatch 可在 reducer 中原子计算多个关联字段
多分支动作迁移useReducer通过显式 action.type 集中管理迁移逻辑,便于单测与排查
跨层级共享下发useState 或 useReducer两者均可放入 Context Provider 中向深层组件分发

React Context + useReducer 与 Vue 3 Pinia 核心特性对照

对比维度React Context + useReducerVue 3 Pinia
集成方式React 内置 API,零额外依赖独立状态库,需单独安装注册
状态定义useReducer 初始值或惰性初始化函数store 中的 state: () => ({}) 工厂
状态更新方式调用 dispatch({ type, payload }) 经纯函数计算直接修改响应式字段或调用 actions 方法
派生计算值借助 useMemo 缓存派生结果内置 getters 自动缓存派生值
更新传播机制Provider 的 value 变化触发消费组件重渲染基于 Proxy 自动细粒度依赖追踪
调试工具支持无专用内置面板(复杂项目常配合 Redux DevTools)Vue DevTools 原生可视化追踪

离线 Chromium 实测 Context 跨层透传、useReducer 迁移、三组件收藏同步与刷新持久化

含完整源码 · 352 行
展开查看收起
python
"""Offline Playwright Chromium lab for React Ch 40: Context + useReducer Global Favorites & Persistence."""
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 Context + useReducer Favorites Lab</title>
<style>
.navbar { display: flex; justify-content: space-between; padding: 12px 20px; border-bottom: 1px solid #ddd; }
.fav-badge { background: #ef4444; color: #fff; border-radius: 12px; padding: 2px 10px; font-size: 13px; }
.card-link { display: block; border: 1px solid #ddd; padding: 12px; margin: 8px 0; text-decoration: none; color: #222; }
</style>
</head>
<body>
  <div id="theme-ctx-root"></div>
  <div id="blog-root"></div>

<script>
// 1. Minimal createContext / Provider / useContext runtime
function createContext(defaultValue) {
  return { _currentValue: defaultValue };
}
function useContext(ctx) {
  return ctx._currentValue;
}

// Pure favoriteReducer matching chapter code
function favoriteReducer(state, action) {
  switch (action.type) {
    case "TOGGLE":
      if (state.includes(action.id)) {
        return state.filter((id) => id !== action.id);
      } else {
        return [...state, action.id];
      }
    case "CLEAR":
      return [];
    default:
      return state;
  }
}

// Case 1 helper: ThemeContext skipping 3 intermediate layers + Provider guard check
const ThemeContext = createContext(null);
const FavoriteContext = createContext(null);

function useFavorites() {
  const ctx = useContext(FavoriteContext);
  if (!ctx) throw new Error("useFavorites 必须在 FavoriteProvider 内部使用");
  return ctx;
}

window.runContextAndGuardCheck = () => {
  // Guard check outside Provider
  let outsideError = null;
  try {
    useFavorites();
  } catch (err) {
    outsideError = err.message;
  }

  // Deeply nested ThemeContext broadcast A -> B -> C -> ThemedButton
  let theme = "light";
  const toggleTheme = () => { theme = theme === "light" ? "dark" : "light"; renderThemeTree(); };
  function ThemedButton() {
    const ctx = useContext(ThemeContext);
    const btn = document.createElement("button");
    btn.id = "theme-ctx-btn";
    btn.textContent = `当前主题:${ctx.theme}`;
    btn.addEventListener("click", ctx.toggleTheme);
    return btn;
  }
  function LayerC() { const d = document.createElement("div"); d.appendChild(ThemedButton()); return d; }
  function LayerB() { const d = document.createElement("div"); d.appendChild(LayerC()); return d; }
  function LayerA() { const d = document.createElement("div"); d.appendChild(LayerB()); return d; }
  function renderThemeTree() {
    ThemeContext._currentValue = { theme, toggleTheme };
    document.getElementById("theme-ctx-root").replaceChildren(LayerA());
  }
  renderThemeTree();
  const initialLabel = document.getElementById("theme-ctx-btn").textContent;
  document.getElementById("theme-ctx-btn").click();
  const toggledLabel = document.getElementById("theme-ctx-btn").textContent;

  return { outsideError, initialLabel, toggledLabel };
};

// Case 2 helper: Pure useReducer dispatch transitions
window.runReducerUnitCheck = () => {
  let st = [];
  const s1 = favoriteReducer(st, { type: "TOGGLE", id: 1 });
  const s2 = favoriteReducer(s1, { type: "TOGGLE", id: 2 });
  const s3 = favoriteReducer(s2, { type: "TOGGLE", id: 1 });
  const sUnknown = favoriteReducer(s3, { type: "NOOP" });
  const s4 = favoriteReducer(s3, { type: "CLEAR" });
  return {
    afterAdd1: s1,
    afterAdd2: s2,
    afterRemove1: s3,
    unknownPreservesRef: sUnknown === s3,
    afterClear: s4
  };
};

// Cases 3 & 4: Integrated FavoriteProvider wrapping Router (NavBar + HomePage/BlogCard + PostPage)
const ARTICLES = [
  { id: 1, title: "React 入门完全指南", summary: "从零学 React Hooks", category: "React", date: "2024-05-10" },
  { id: 2, title: "JS 异步编程详解", summary: "搞懂 Promise 与异步", category: "JavaScript", date: "2024-05-08" },
  { id: 3, title: "CSS Grid 布局实战", summary: "掌握二维网格布局", category: "CSS", date: "2024-05-05" }
];

let favoriteIds = (() => {
  const saved = localStorage.getItem("blog-favorites");
  return saved ? JSON.parse(saved) : [];
})();
let currentPath = "/";

function dispatchFavorite(action) {
  favoriteIds = favoriteReducer(favoriteIds, action);
  localStorage.setItem("blog-favorites", JSON.stringify(favoriteIds));
  renderBlog();
}

function renderNavBar() {
  const { favoriteCount } = useFavorites();
  const header = document.createElement("header");
  header.className = "navbar";
  const badge = favoriteCount > 0 ? `<span id="nav-fav-badge" class="fav-badge">收藏 ${favoriteCount}</span>` : "";
  header.innerHTML = `<span class="logo">BlueSky Blog</span><nav><a id="nav-home" href="/">首页</a> ${badge}</nav>`;
  header.querySelector("#nav-home").addEventListener("click", (e) => {
    e.preventDefault();
    currentPath = "/";
    renderBlog();
  });
  return header;
}

function renderBlogCard(article) {
  const { isFavorite, toggleFavorite } = useFavorites();
  const link = document.createElement("a");
  link.href = `/post/${article.id}`;
  link.className = "card-link";
  link.dataset.id = String(article.id);
  link.innerHTML = `<h3>${article.title}</h3><p>${article.summary}</p>`;
  const btn = document.createElement("button");
  btn.className = "fav-btn";
  btn.dataset.favId = String(article.id);
  btn.textContent = isFavorite(article.id) ? "♥" : "♡";
  btn.addEventListener("click", (e) => {
    e.preventDefault();
    e.stopPropagation();
    toggleFavorite(article.id);
  });
  link.appendChild(btn);
  link.addEventListener("click", (e) => {
    e.preventDefault();
    currentPath = `/post/${article.id}`;
    renderBlog();
  });
  return link;
}

function renderPostPage(id) {
  const { isFavorite, toggleFavorite } = useFavorites();
  const article = ARTICLES.find((a) => a.id === Number(id));
  const art = document.createElement("article");
  art.className = "post-view";
  art.innerHTML = `<h1>${article.title}</h1>`;
  const btn = document.createElement("button");
  btn.id = "post-fav-btn";
  btn.textContent = isFavorite(article.id) ? "♥ 已收藏" : "♡ 收藏";
  btn.addEventListener("click", () => toggleFavorite(article.id));
  art.appendChild(btn);
  return art;
}

function renderBlog() {
  FavoriteContext._currentValue = {
    favoriteIds,
    favoriteCount: favoriteIds.length,
    toggleFavorite: (id) => dispatchFavorite({ type: "TOGGLE", id }),
    isFavorite: (id) => favoriteIds.includes(id)
  };
  const root = document.getElementById("blog-root");
  const app = document.createElement("div");
  app.appendChild(renderNavBar());
  const main = document.createElement("main");
  if (currentPath === "/") {
    ARTICLES.forEach((a) => main.appendChild(renderBlogCard(a)));
  } else {
    const id = currentPath.split("/")[2];
    main.appendChild(renderPostPage(id));
  }
  app.appendChild(main);
  root.replaceChildren(app);
}

window.getCurrentPath = () => currentPath;
window.mountFavoriteApp = () => renderBlog();
</script>
</body>
</html>
"""


class LabHandler(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), LabHandler)
    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()
            page.goto(f"http://127.0.0.1:{port}/")

            # Case 1: Context broadcast skipping intermediate layers + guard outside Provider
            c1_actual = page.evaluate("() => window.runContextAndGuardCheck()")
            c1_expected = {
                "outsideError": "useFavorites 必须在 FavoriteProvider 内部使用",
                "initialLabel": "当前主题:light",
                "toggledLabel": "当前主题:dark",
            }
            cases.append({
                "name": "context_provider_broadcast_and_guard",
                "expected": c1_expected,
                "actual": c1_actual,
                "passed": c1_actual == c1_expected,
            })

            # Case 2: Pure reducer transitions
            c2_actual = page.evaluate("() => window.runReducerUnitCheck()")
            c2_expected = {
                "afterAdd1": [1],
                "afterAdd2": [1, 2],
                "afterRemove1": [2],
                "unknownPreservesRef": True,
                "afterClear": [],
            }
            cases.append({
                "name": "usereducer_toggle_and_clear",
                "expected": c2_expected,
                "actual": c2_actual,
                "passed": c2_actual == c2_expected,
            })

            # Case 3: Cross-component sync across BlogCard, PostPage, and NavBar
            page.evaluate("() => window.mountFavoriteApp()")
            badge_init = page.locator("#nav-fav-badge").count()
            # Click favorite button inside BlogCard #1 -> preventDefault keeps route at '/'
            page.locator('button.fav-btn[data-fav-id="1"]').click()
            path_after_card_fav = page.evaluate("() => window.getCurrentPath()")
            card1_icon = page.locator('button.fav-btn[data-fav-id="1"]').inner_text()
            nav_badge_1 = page.locator("#nav-fav-badge").inner_text()
            # Open PostPage #1 -> should show "♥ 已收藏"
            page.locator('.card-link[data-id="1"] h3').click()
            post_btn_fav = page.locator("#post-fav-btn").inner_text()
            # Unfavorite on PostPage -> hides NavBar badge
            page.locator("#post-fav-btn").click()
            post_btn_unfav = page.locator("#post-fav-btn").inner_text()
            badge_after_unfav = page.locator("#nav-fav-badge").count()
            c3_actual = {
                "badge_init": badge_init,
                "path_after_card_fav": path_after_card_fav,
                "card1_icon": card1_icon,
                "nav_badge_1": nav_badge_1,
                "post_btn_fav": post_btn_fav,
                "post_btn_unfav": post_btn_unfav,
                "badge_after_unfav": badge_after_unfav,
            }
            c3_expected = {
                "badge_init": 0,
                "path_after_card_fav": "/",
                "card1_icon": "♥",
                "nav_badge_1": "收藏 1",
                "post_btn_fav": "♥ 已收藏",
                "post_btn_unfav": "♡ 收藏",
                "badge_after_unfav": 0,
            }
            cases.append({
                "name": "favorites_cross_component_sync",
                "expected": c3_expected,
                "actual": c3_actual,
                "passed": c3_actual == c3_expected,
            })

            # Case 4: localStorage persistence across full page reload
            page.locator("#nav-home").click()
            page.locator('button.fav-btn[data-fav-id="1"]').click()
            page.locator('button.fav-btn[data-fav-id="3"]').click()
            stored_json = page.evaluate("() => localStorage.getItem('blog-favorites')")
            page.reload()
            page.evaluate("() => window.mountFavoriteApp()")
            reloaded_badge = page.locator("#nav-fav-badge").inner_text()
            reloaded_card1 = page.locator('button.fav-btn[data-fav-id="1"]').inner_text()
            reloaded_card2 = page.locator('button.fav-btn[data-fav-id="2"]').inner_text()
            reloaded_card3 = page.locator('button.fav-btn[data-fav-id="3"]').inner_text()
            c4_actual = {
                "stored_json": stored_json,
                "reloaded_badge": reloaded_badge,
                "reloaded_icons": [reloaded_card1, reloaded_card2, reloaded_card3],
            }
            c4_expected = {
                "stored_json": "[1,3]",
                "reloaded_badge": "收藏 2",
                "reloaded_icons": ["♥", "♡", "♥"],
            }
            cases.append({
                "name": "favorites_localstorage_reload_persistence",
                "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()
核对跨 3 层主题切换与 Provider 外调用报错守卫、TOGGLE/CLEAR 纯函数迁移、卡片点击 preventDefault 同步导航栏/详情页,以及 localStorage '[1,3]' 刷新还原。

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

本地运行

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

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

本章附件与实例包

下载课程关联工程包:React

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

下载课程关联工程包:React

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

常见错误与边界检查

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

技术规范与官方资料

练习与参考解答

查看参考解答

因为导航栏 `NavBar` 与各个路由页面都位于 `RouterProvider` 渲染树内部,只有将 `FavoriteProvider` 置于其外层,所有页面与导航栏才能共享同一份收藏上下文;`BlogCard` 外层由 `<Link>` 包裹,调用 `e.preventDefault()` 可阻止点击收藏按钮时误触发路由跳转。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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