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

在无头 Chromium 中离线验证核心 Hooks 行为、useLayoutEffect 时序、自定义 Hook 隔离与条件调用错位机理

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-hooks.py
explore-hooks.py303 行
"""Offline Playwright Chromium verification for React Ch30 (hooks)."""
import json
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")


def case_usestate_and_useeffect_title_and_cleanup(page):
    html = """<!doctype html>
<html><head><meta charset="utf-8"><title>Initial</title></head>
<body>
  <p id="cnt-text"></p>
  <button id="inc">Click me</button>
  <button id="noop-other">Other</button>
  <p id="timer-text"></p>
  <script>
    let count = 0, other = 0, titleEffectRuns = 0;
    let prevCountDep = undefined;
    function renderExample() {
      document.getElementById('cnt-text').textContent = `You clicked ${count} times`;
      if (prevCountDep !== count) {
        prevCountDep = count;
        titleEffectRuns += 1;
        document.title = `You clicked ${count} times`;
      }
    }
    document.getElementById('inc').addEventListener('click', () => { count += 1; renderExample(); });
    document.getElementById('noop-other').addEventListener('click', () => { other += 1; renderExample(); });
    renderExample();

    // Timer with useEffect(..., []) + cleanup
    let seconds = 0, cleanupCalled = false;
    const timerId = setInterval(() => {
      seconds += 1;
      document.getElementById('timer-text').textContent = `Timer: ${seconds} seconds`;
    }, 30);
    window.__unmountTimer = () => {
      clearInterval(timerId);
      cleanupCalled = true;
    };
    window.__getRes = () => ({
      title: document.title,
      cntText: document.getElementById('cnt-text').textContent,
      titleEffectRuns,
      cleanupCalled,
      seconds,
    });
  </script>
</body></html>"""
    page.set_content(html)
    page.click("#inc")
    page.click("#inc")
    page.click("#noop-other")
    page.wait_for_function("window.__getRes().seconds >= 2")
    page.evaluate("window.__unmountTimer()")
    sec_at_unmount = page.evaluate("window.__getRes().seconds")
    page.wait_for_timeout(90)
    res = page.evaluate("window.__getRes()")
    actual = {
        "title": res["title"],
        "cntText": res["cntText"],
        "titleEffectRuns": res["titleEffectRuns"],
        "cleanupCalled": res["cleanupCalled"],
        "ticksStoppedAfterUnmount": res["seconds"] == sec_at_unmount,
    }
    expected = {
        "title": "You clicked 2 times",
        "cntText": "You clicked 2 times",
        "titleEffectRuns": 3,
        "cleanupCalled": True,
        "ticksStoppedAfterUnmount": True,
    }
    return dict(name="usestate_and_useeffect_title_and_cleanup", expected=expected, actual=actual, passed=(actual == expected))


def case_usecontext_and_usereducer_state_flow(page):
    html = """<!doctype html>
<html><head><meta charset="utf-8"></head>
<body>
  <div id="badge"></div>
  <div id="sum"></div>
  <script>
    function createContext(defaultValue) { return { _current: defaultValue }; }
    function useContext(ctx) { return ctx._current; }
    const ThemeContext = createContext('light');
    ThemeContext._current = 'ocean-dark';
    const consumedTheme = useContext(ThemeContext);
    document.getElementById('badge').textContent = `theme=${consumedTheme}`;

    function reducer(state, action) {
      switch (action.type) {
        case 'increment': return { count: state.count + 1, history: [...state.history, '+1'] };
        case 'add': return { count: state.count + action.payload, history: [...state.history, '+' + action.payload] };
        case 'reset': return { count: 0, history: [...state.history, 'reset'] };
        default: return state;
      }
    }
    let state = { count: 0, history: [] };
    const dispatch = (action) => { state = reducer(state, action); };
    dispatch({ type: 'increment' });
    dispatch({ type: 'add', payload: 4 });
    const mid = state.count;
    dispatch({ type: 'reset' });
    dispatch({ type: 'add', payload: 3 });
    document.getElementById('sum').textContent = String(state.count);
    window.__res = {
      theme: document.getElementById('badge').textContent,
      midCount: mid,
      finalCount: state.count,
      history: state.history,
    };
  </script>
</body></html>"""
    page.set_content(html)
    actual = page.evaluate("window.__res")
    expected = {
        "theme": "theme=ocean-dark",
        "midCount": 5,
        "finalCount": 3,
        "history": ["+1", "+4", "reset", "+3"],
    }
    return dict(name="usecontext_and_usereducer_state_flow", expected=expected, actual=actual, passed=(actual == expected))


def case_usememo_usecallback_useref_layout_order(page):
    html = """<!doctype html>
<html><head><meta charset="utf-8"></head>
<body>
  <div id="box" style="width:120px;height:40px"></div>
  <script>
    const order = [];
    let computeRuns = 0;
    let memoValCache = null, memoValDeps = null;
    function useMemo(fn, deps) {
      if (memoValDeps && deps.every((d, i) => Object.is(d, memoValDeps[i]))) return memoValCache;
      memoValDeps = deps.slice();
      computeRuns += 1;
      memoValCache = fn();
      return memoValCache;
    }
    let cbCache = null, cbDeps = null;
    function useCallback(fn, deps) {
      if (cbDeps && deps.every((d, i) => Object.is(d, cbDeps[i]))) return cbCache;
      cbDeps = deps.slice();
      cbCache = fn;
      return cbCache;
    }
    const renderRef = { current: 0 };

    // Simulate 2 renders with same dep a=5, then 1 render with a=7
    const f1 = useCallback(() => 'ok', [5]);
    const v1 = useMemo(() => 5 * 10, [5]);
    renderRef.current += 1;
    const f2 = useCallback(() => 'ok', [5]);
    const v2 = useMemo(() => 5 * 10, [5]);
    renderRef.current += 1;
    const v3 = useMemo(() => 7 * 10, [7]);
    renderRef.current += 1;

    // useImperativeHandle restricted facade
    const boxEl = document.getElementById('box');
    const handle = { getWidth: () => boxEl.getBoundingClientRect().width };

    // useLayoutEffect runs synchronously after DOM commit, before rAF/useEffect
    order.push('render');
    // synchronous layout effect
    const measuredWidth = handle.getWidth();
    order.push('layoutEffect');
    window.__done = new Promise((resolve) => {
      requestAnimationFrame(() => {
        order.push('effect');
        resolve({
          sameCallbackRef: f1 === f2,
          memoValues: [v1, v2, v3],
          computeRuns,
          refRenders: renderRef.current,
          measuredWidth,
          executionOrder: order,
        });
      });
    });
  </script>
</body></html>"""
    page.set_content(html)
    actual = page.evaluate("window.__done")
    expected = {
        "sameCallbackRef": True,
        "memoValues": [50, 50, 70],
        "computeRuns": 2,
        "refRenders": 3,
        "measuredWidth": 120,
        "executionOrder": ["render", "layoutEffect", "effect"],
    }
    return dict(name="usememo_usecallback_useref_layout_order", expected=expected, actual=actual, passed=(actual == expected))


def case_custom_hook_reuse_and_top_level_order_rule(page):
    html = """<!doctype html>
<html><head><meta charset="utf-8"></head>
<body>
  <script>
    // Minimal React fiber-like Hook cursor showing custom hook isolation & why conditional hooks corrupt slots
    function createFiber() {
      return { hooks: [], cursor: 0, debugLabels: [] };
    }
    let activeFiber = null;
    function useState(init) {
      const f = activeFiber;
      const idx = f.cursor++;
      if (f.hooks.length <= idx) f.hooks.push(init);
      return [f.hooks[idx], (val) => { f.hooks[idx] = typeof val === 'function' ? val(f.hooks[idx]) : val; }];
    }
    function useDebugValue(label) {
      activeFiber.debugLabels.push(label);
    }
    function useCounter(initial, step) {
      const [val, setVal] = useState(initial);
      useDebugValue(`counter:${val}`);
      return { val, inc: () => setVal((c) => c + step) };
    }

    const fiberA = createFiber();
    const fiberB = createFiber();
    function renderCounter(fiber, initial, step) {
      activeFiber = fiber;
      fiber.cursor = 0;
      fiber.debugLabels = [];
      return useCounter(initial, step);
    }
    let a = renderCounter(fiberA, 10, 5);
    a.inc();
    a = renderCounter(fiberA, 10, 5);
    let b = renderCounter(fiberB, 0, 1);
    b.inc();
    b = renderCounter(fiberB, 0, 1);

    // Demonstrate Hook slot shift when calling useState inside an `if` branch
    const badFiber = createFiber();
    function brokenComponent(cond) {
      activeFiber = badFiber;
      badFiber.cursor = 0;
      let first = null;
      if (cond) {
        [first] = useState('A');
      }
      const [second] = useState('B');
      return { first, second };
    }
    const r1 = brokenComponent(true);  // slot0='A', slot1='B'
    const r2 = brokenComponent(false); // slot0 read as `second` -> wrongly gets 'A'!
    window.__res = {
      compA: a.val,
      compB: b.val,
      debugA: fiberA.debugLabels[0],
      debugB: fiberB.debugLabels[0],
      validFirstRender: r1,
      conditionalHookCorruptedSecond: r2.second,
    };
  </script>
</body></html>"""
    page.set_content(html)
    actual = page.evaluate("window.__res")
    expected = {
        "compA": 15,
        "compB": 1,
        "debugA": "counter:15",
        "debugB": "counter:1",
        "validFirstRender": {"first": "A", "second": "B"},
        "conditionalHookCorruptedSecond": "A",
    }
    return dict(name="custom_hook_reuse_and_top_level_order_rule", expected=expected, actual=actual, passed=(actual == expected))


def main():
    with sync_playwright() as p:
        browser = launch_browser(p)
        try:
            page = browser.new_page()
            cases = [
                case_usestate_and_useeffect_title_and_cleanup(page),
                case_usecontext_and_usereducer_state_flow(page),
                case_usememo_usecallback_useref_layout_order(page),
                case_custom_hook_reuse_and_top_level_order_rule(page),
            ]
        finally:
            browser.close()
    print(json.dumps({"cases": cases}, ensure_ascii=False))


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

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

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

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

下载课程关联工程包:React

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

下载课程关联工程包:React

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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