蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

离线 Chromium 实测 useState 重渲染、不可变数组/对象更新、useMemo 缓存与博客分类筛选

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-blog-usestate.py
explore-blog-usestate.py386 行
"""Offline Playwright Chromium lab for React Ch 34: useState, Immutability, useMemo & Category Filter."""
import json
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 useState & useMemo Offline Lab</title>
<style>
.category-bar { display: flex; gap: 10px; margin-bottom: 16px; }
.category-bar button { padding: 6px 16px; border: 1px solid #ddd; border-radius: 20px; background: #fff; cursor: pointer; }
.category-bar button.active { background: #1976d2; color: #fff; border-color: #1976d2; }
</style>
</head>
<body>
  <section id="counter-root"></section>
  <section id="todo-root"></section>
  <section id="memo-root"></section>
  <section id="blog-root"></section>

<script>
// Minimal offline Hooks runtime modeling React re-render, Object.is bailout, and useMemo shallow deps
function createHookApp(container, Component) {
  const slots = [];
  let cursor = 0;
  let renderCount = 0;

  function useState(initial) {
    const idx = cursor++;
    if (!(idx in slots)) {
      slots[idx] = typeof initial === "function" ? initial() : initial;
    }
    const setState = (nextOrFn) => {
      const prev = slots[idx];
      const next = typeof nextOrFn === "function" ? nextOrFn(prev) : nextOrFn;
      if (!Object.is(prev, next)) {
        slots[idx] = next;
        render();
      }
    };
    return [slots[idx], setState];
  }

  function useMemo(factory, deps) {
    const idx = cursor++;
    const prev = slots[idx];
    const unchanged = prev && deps && prev.deps.length === deps.length && deps.every((d, i) => Object.is(d, prev.deps[i]));
    if (unchanged) return prev.value;
    const value = factory();
    slots[idx] = { value, deps: [...deps] };
    return value;
  }

  function render() {
    cursor = 0;
    renderCount += 1;
    const node = Component({ useState, useMemo, getRenderCount: () => renderCount });
    container.replaceChildren(node);
  }

  render();
  return { getRenderCount: () => renderCount };
}

// 1. Counter & read-only state demonstration
const counterApp = createHookApp(document.getElementById("counter-root"), ({ useState }) => {
  const [count, setCount] = useState(0);
  let [title, setTitle] = useState("默认标题");
  const div = document.createElement("div");
  div.innerHTML = `<p id="cnt-val">点击次数:${count}</p><p id="title-val">${title}</p>`;
  const bInc = document.createElement("button");
  bInc.id = "btn-inc";
  bInc.textContent = "+1";
  bInc.addEventListener("click", () => setCount(count + 1));

  const bBad = document.createElement("button");
  bBad.id = "btn-direct-mutate";
  bBad.textContent = "错误直接赋值";
  bBad.addEventListener("click", () => { title = "未通知React的标题"; });

  const bGood = document.createElement("button");
  bGood.id = "btn-set-title";
  bGood.textContent = "修改标题";
  bGood.addEventListener("click", () => setTitle("新标题"));

  div.append(bInc, bBad, bGood);
  return div;
});

// 2. Immutable array & object updates
let todoSnapshots = [];
createHookApp(document.getElementById("todo-root"), ({ useState }) => {
  const [todos, setTodos] = useState([
    { id: 1, text: "学习 React", done: false },
    { id: 2, text: "写博客", done: true }
  ]);
  const [profile, setProfile] = useState({ name: "小明", role: "reader" });
  todoSnapshots.push({ todosRef: todos, profileRef: profile, todosLen: todos.length, name: profile.name });

  const div = document.createElement("div");
  const ul = document.createElement("ul");
  ul.id = "todo-list";
  todos.forEach((t) => {
    const li = document.createElement("li");
    li.dataset.id = String(t.id);
    li.innerHTML = t.done ? `<s>${t.text}</s>` : t.text;
    li.addEventListener("click", () => {
      setTodos(todos.map((item) => (item.id === t.id ? { ...item, done: !item.done } : item)));
    });
    ul.appendChild(li);
  });

  const btnBadPush = document.createElement("button");
  btnBadPush.id = "btn-bad-push";
  btnBadPush.addEventListener("click", () => {
    todos.push({ id: 99, text: "错误push", done: false });
    setTodos(todos); // same reference -> Object.is bailout, no re-render
  });

  const btnAdd = document.createElement("button");
  btnAdd.id = "btn-add-todo";
  btnAdd.addEventListener("click", () => {
    // Clean up any test mutation by creating a fresh array without id 99
    const clean = todos.filter((t) => t.id !== 99);
    setTodos([...clean, { id: 3, text: "部署上线", done: false }]);
  });

  const btnDel = document.createElement("button");
  btnDel.id = "btn-del-todo-2";
  btnDel.addEventListener("click", () => {
    setTodos(todos.filter((t) => t.id !== 2));
  });

  const btnObj = document.createElement("button");
  btnObj.id = "btn-update-obj";
  btnObj.addEventListener("click", () => {
    setProfile({ ...profile, name: "小红" });
  });

  const pProf = document.createElement("p");
  pProf.id = "profile-name";
  pProf.textContent = `${profile.name}:${profile.role}`;

  div.append(ul, pProf, btnBadPush, btnAdd, btnDel, btnObj);
  return div;
});

// 3. useMemo cache verification
let memoComputeCount = 0;
createHookApp(document.getElementById("memo-root"), ({ useState, useMemo }) => {
  const [articles] = useState([
    { id: 1, title: "React 入门", category: "React" },
    { id: 2, title: "Promise 详解", category: "JavaScript" },
    { id: 3, title: "Grid 布局", category: "CSS" },
    { id: 4, title: "React Hooks", category: "React" }
  ]);
  const [activeCategory, setActiveCategory] = useState("全部");
  const [unrelated, setUnrelated] = useState(0);

  const filtered = useMemo(() => {
    memoComputeCount += 1;
    if (activeCategory === "全部") return articles;
    return articles.filter((a) => a.category === activeCategory);
  }, [articles, activeCategory]);

  const div = document.createElement("div");
  div.innerHTML = `<p id="memo-stats">共 ${articles.length} 篇,当前 ${filtered.length} 篇,无关计数 ${unrelated}</p>`;
  const bUnrel = document.createElement("button");
  bUnrel.id = "btn-unrelated";
  bUnrel.addEventListener("click", () => setUnrelated(unrelated + 1));
  const bReact = document.createElement("button");
  bReact.id = "btn-memo-react";
  bReact.addEventListener("click", () => setActiveCategory("React"));
  div.append(bUnrel, bReact);
  return div;
});

// 4. Full Blog Category Filter
createHookApp(document.getElementById("blog-root"), ({ useState, useMemo }) => {
  const [articles] = useState([
    { id: 1, title: "React 入门完全指南", summary: "从零开始学 React", category: "React", date: "2024-05-10" },
    { id: 2, title: "JS 异步编程详解", summary: "搞懂 Promise 和 async/await", category: "JavaScript", date: "2024-05-08" },
    { id: 3, title: "CSS Grid 布局实战", summary: "用 Grid 实现响应式布局", category: "CSS", date: "2024-05-05" },
    { id: 4, title: "React Hooks 深入", summary: "深入理解 useState 和 useEffect", category: "React", date: "2024-05-03" },
    { id: 5, title: "Flexbox 完全指南", summary: "一文学会弹性布局", category: "CSS", date: "2024-05-01" }
  ]);
  const [activeCategory, setActiveCategory] = useState("全部");
  const categories = useMemo(() => ["全部", ...new Set(articles.map((a) => a.category))], [articles]);
  const filteredArticles = useMemo(
    () => (activeCategory === "全部" ? articles : articles.filter((a) => a.category === activeCategory)),
    [articles, activeCategory]
  );

  const div = document.createElement("div");
  const bar = document.createElement("div");
  bar.className = "category-bar";
  categories.forEach((cat) => {
    const btn = document.createElement("button");
    btn.dataset.cat = cat;
    btn.className = activeCategory === cat ? "active" : "";
    btn.textContent = cat;
    btn.addEventListener("click", () => setActiveCategory(cat));
    bar.appendChild(btn);
  });
  const info = document.createElement("p");
  info.id = "blog-result-info";
  info.textContent = `共 ${filteredArticles.length} 篇`;
  const grid = document.createElement("div");
  grid.id = "blog-cards";
  filteredArticles.forEach((a) => {
    const card = document.createElement("div");
    card.className = "article-card";
    card.textContent = a.title;
    grid.appendChild(card);
  });
  div.append(bar, info, grid);
  return div;
});

window.getMetrics = () => ({
  counterRenders: counterApp.getRenderCount(),
  memoComputeCount,
  todoRenderCount: todoSnapshots.length,
  firstTwoRefsDifferent: todoSnapshots.length >= 2 ? todoSnapshots[0].todosRef !== todoSnapshots[1].todosRef : false,
  lastProfileRefDifferent: todoSnapshots.length >= 2 ? todoSnapshots[0].profileRef !== todoSnapshots[todoSnapshots.length - 1].profileRef : false
});
</script>
</body>
</html>
"""


def main():
    cases = []
    with sync_playwright() as p:
        browser = launch_browser(p)
        page = browser.new_page()
        page.set_content(HTML)

        # Case 1: useState re-render & read-only mutation check
        page.locator("#btn-inc").click()
        page.locator("#btn-inc").click()
        renders_before_bad = page.evaluate("() => window.getMetrics().counterRenders")
        page.locator("#btn-direct-mutate").click()
        renders_after_bad = page.evaluate("() => window.getMetrics().counterRenders")
        title_after_bad = page.locator("#title-val").inner_text()
        page.locator("#btn-set-title").click()
        c1_actual = {
            "count_text": page.locator("#cnt-val").inner_text(),
            "renders_before_bad": renders_before_bad,
            "renders_after_bad": renders_after_bad,
            "title_after_bad": title_after_bad,
            "title_after_setter": page.locator("#title-val").inner_text(),
            "renders_after_setter": page.evaluate("() => window.getMetrics().counterRenders"),
        }
        c1_expected = {
            "count_text": "点击次数:2",
            "renders_before_bad": 3,
            "renders_after_bad": 3,
            "title_after_bad": "默认标题",
            "title_after_setter": "新标题",
            "renders_after_setter": 4,
        }
        cases.append({
            "name": "usestate_rerender_and_readonly",
            "expected": c1_expected,
            "actual": c1_actual,
            "passed": c1_actual == c1_expected,
        })

        # Case 2: Immutable array & object updates vs push bailout
        before_bad_push = page.locator("#todo-list li").count()
        page.locator("#btn-bad-push").click()
        after_bad_push = page.locator("#todo-list li").count()
        page.locator("#btn-add-todo").click()
        page.locator('#todo-list li[data-id="1"]').click()
        page.locator("#btn-del-todo-2").click()
        page.locator("#btn-update-obj").click()
        li_html = page.locator("#todo-list li").evaluate_all("els => els.map(e => e.innerHTML)")
        metrics = page.evaluate("() => window.getMetrics()")
        c2_actual = {
            "before_bad_push": before_bad_push,
            "after_bad_push": after_bad_push,
            "final_todos_html": li_html,
            "profile_name": page.locator("#profile-name").inner_text(),
            "new_array_ref": metrics["firstTwoRefsDifferent"],
            "new_obj_ref": metrics["lastProfileRefDifferent"],
        }
        c2_expected = {
            "before_bad_push": 2,
            "after_bad_push": 2,
            "final_todos_html": ["<s>学习 React</s>", "部署上线"],
            "profile_name": "小红:reader",
            "new_array_ref": True,
            "new_obj_ref": True,
        }
        cases.append({
            "name": "immutable_array_and_object_updates",
            "expected": c2_expected,
            "actual": c2_actual,
            "passed": c2_actual == c2_expected,
        })

        # Case 3: useMemo cache hit on unrelated state vs recompute on activeCategory
        init_computes = page.evaluate("() => window.getMetrics().memoComputeCount")
        page.locator("#btn-unrelated").click()
        page.locator("#btn-unrelated").click()
        after_unrel_computes = page.evaluate("() => window.getMetrics().memoComputeCount")
        page.locator("#btn-memo-react").click()
        after_cat_computes = page.evaluate("() => window.getMetrics().memoComputeCount")
        c3_actual = {
            "init_computes": init_computes,
            "after_unrelated_computes": after_unrel_computes,
            "after_category_computes": after_cat_computes,
            "memo_stats": page.locator("#memo-stats").inner_text(),
        }
        c3_expected = {
            "init_computes": 1,
            "after_unrelated_computes": 1,
            "after_category_computes": 2,
            "memo_stats": "共 4 篇,当前 2 篇,无关计数 2",
        }
        cases.append({
            "name": "usememo_cache_and_deps",
            "expected": c3_expected,
            "actual": c3_actual,
            "passed": c3_actual == c3_expected,
        })

        # Case 4: Blog category filter interactive transitions
        categories = page.locator("#blog-root .category-bar button").all_inner_texts()
        init_info = page.locator("#blog-result-info").inner_text()
        page.locator('#blog-root .category-bar button[data-cat="React"]').click()
        react_active = page.locator('#blog-root .category-bar button.active').inner_text()
        react_info = page.locator("#blog-result-info").inner_text()
        react_titles = page.locator("#blog-cards .article-card").all_inner_texts()
        page.locator('#blog-root .category-bar button[data-cat="CSS"]').click()
        css_info = page.locator("#blog-result-info").inner_text()
        page.locator('#blog-root .category-bar button[data-cat="JavaScript"]').click()
        js_info = page.locator("#blog-result-info").inner_text()
        page.locator('#blog-root .category-bar button[data-cat="全部"]').click()
        all_info = page.locator("#blog-result-info").inner_text()
        c4_actual = {
            "categories": categories,
            "init_info": init_info,
            "react_active": react_active,
            "react_info": react_info,
            "react_titles": react_titles,
            "css_info": css_info,
            "js_info": js_info,
            "all_info": all_info,
        }
        c4_expected = {
            "categories": ["全部", "React", "JavaScript", "CSS"],
            "init_info": "共 5 篇",
            "react_active": "React",
            "react_info": "共 2 篇",
            "react_titles": ["React 入门完全指南", "React Hooks 深入"],
            "css_info": "共 2 篇",
            "js_info": "共 1 篇",
            "all_info": "共 5 篇",
        }
        cases.append({
            "name": "blog_category_filter_interactive",
            "expected": c4_expected,
            "actual": c4_actual,
            "passed": c4_actual == c4_expected,
        })

        browser.close()

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


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

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

入口文件:projects/react-blog-usestate-lab/explore-blog-usestate.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-blog-usestate.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:React

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

下载课程关联工程包:React

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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