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

离线 Chromium 验证类/Hook 状态批处理、Clock 挂载卸载链路与多实例隔离

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-state.py
explore-state.py326 行
"""Offline Chromium lab for React Ch 14: state."""
import json
from playwright.sync_api import sync_playwright

HTML = """<!doctype html>
<html lang="zh-CN">
<head><meta charset="utf-8"><title>React State Lab</title></head>
<body>
  <div id="counter-class-root"></div>
  <div id="counter-hook-root"></div>
  <div id="clock-root"></div>
  <div id="flow-root"></div>
  <div id="multi-root"></div>
  <script>
    'use strict';

    function createElement(type, props, ...children) {
      const flat = children.flat(Infinity).filter(c => c !== null && c !== undefined && c !== false);
      return { type, props: Object.assign({}, props || {}, { children: flat }) };
    }

    function renderVNode(vnode) {
      if (typeof vnode === 'string' || typeof vnode === 'number') return document.createTextNode(String(vnode));
      if (typeof vnode.type === 'function') {
        const frozenProps = Object.freeze(Object.assign({}, vnode.props));
        return renderVNode(vnode.type(frozenProps));
      }
      const el = document.createElement(vnode.type);
      for (const [k, v] of Object.entries(vnode.props)) {
        if (k === 'children' || v === undefined || v === null) continue;
        if (k.startsWith('on') && typeof v === 'function') el.addEventListener(k.slice(2).toLowerCase(), v);
        else el.setAttribute(k === 'className' ? 'class' : k, String(v));
      }
      vnode.props.children.forEach(c => el.appendChild(renderVNode(c)));
      return el;
    }

    // Minimal Class Component host supporting batched setState, mount & unmount
    class Component {
      constructor(props) {
        this.props = Object.freeze(Object.assign({}, props || {}));
        this.state = {};
        this._queue = [];
        this._batching = false;
        this._container = null;
      }
      setState(updater) {
        this._queue.push(updater);
        if (!this._batching) this._flush();
      }
      _flush() {
        let next = Object.assign({}, this.state);
        const q = this._queue.splice(0);
        for (const u of q) {
          const partial = typeof u === 'function' ? u(next, this.props) : u;
          next = Object.assign({}, next, partial);
        }
        this.state = next;
        this._commit();
      }
      _commit() {
        if (!this._container) return;
        this._container.innerHTML = '';
        this._container.appendChild(renderVNode(this.render()));
      }
      _mount(container) {
        this._container = container;
        this._commit();
        if (typeof this.componentDidMount === 'function') this.componentDidMount();
      }
      _unmount() {
        if (typeof this.componentWillUnmount === 'function') this.componentWillUnmount();
        if (this._container) this._container.innerHTML = '';
        this._container = null;
      }
    }

    window.runLab = function () {
      // Case 1: Class Counter + Function useState Counter + Batched setState functional vs object updater
      class ClassCounter extends Component {
        constructor(props) {
          super(props);
          this.state = { count: 0 };
        }
        increment = () => {
          this.setState(prev => ({ count: prev.count + 1 }));
        };
        batchObjectThree = () => {
          this._batching = true;
          this.setState({ count: this.state.count + 1 });
          this.setState({ count: this.state.count + 1 });
          this.setState({ count: this.state.count + 1 });
          this._batching = false;
          this._flush();
        };
        batchFunctionalThree = () => {
          this._batching = true;
          this.setState(prev => ({ count: prev.count + 1 }));
          this.setState(prev => ({ count: prev.count + 1 }));
          this.setState(prev => ({ count: prev.count + 1 }));
          this._batching = false;
          this._flush();
        };
        render() {
          return createElement(
            'div', null,
            createElement('p', { id: 'cls-count' }, 'Count: ', this.state.count),
            createElement('button', { id: 'cls-inc', onClick: this.increment }, 'Increment')
          );
        }
      }
      const clsCounter = new ClassCounter({});
      clsCounter._mount(document.getElementById('counter-class-root'));
      document.getElementById('cls-inc').click();
      document.getElementById('cls-inc').click();
      const afterTwoClicks = document.getElementById('cls-count').textContent;
      clsCounter.batchObjectThree();
      const afterBatchObj = document.getElementById('cls-count').textContent;
      clsCounter.batchFunctionalThree();
      const afterBatchFn = document.getElementById('cls-count').textContent;

      // Function component with useState hook
      const hookRoot = document.getElementById('counter-hook-root');
      let hookState = 0;
      function useState(init) {
        const setVal = (v) => {
          hookState = typeof v === 'function' ? v(hookState) : v;
          renderHook();
        };
        return [hookState, setVal];
      }
      function HookCounter() {
        const [count, setCount] = useState(0);
        return createElement(
          'div', null,
          createElement('p', { id: 'hook-count' }, 'Count: ', count),
          createElement('button', { id: 'hook-inc', onClick: () => setCount(c => c + 1) }, 'Increment')
        );
      }
      function renderHook() {
        hookRoot.innerHTML = '';
        hookRoot.appendChild(renderVNode(HookCounter()));
      }
      renderHook();
      document.getElementById('hook-inc').click();
      document.getElementById('hook-inc').click();
      document.getElementById('hook-inc').click();
      const hookFinal = document.getElementById('hook-count').textContent;

      const case1 = {
        class_after_2_clicks: afterTwoClicks,
        class_after_batched_object_x3: afterBatchObj,
        class_after_batched_functional_x3: afterBatchFn,
        hook_after_3_clicks: hookFinal
      };

      // Case 2: Clock constructor -> render -> componentDidMount -> tick/setState -> render -> componentWillUnmount
      const trace = [];
      let timerCleared = false;
      class Clock extends Component {
        constructor(props) {
          super(props);
          trace.push('constructor');
          this.state = { time: '08:00:00' };
          this.timerID = null;
        }
        componentDidMount() {
          trace.push('componentDidMount');
          this.timerID = 42;
        }
        tick(nextTime) {
          trace.push('tick->setState');
          this.setState({ time: nextTime });
        }
        componentWillUnmount() {
          trace.push('componentWillUnmount');
          if (this.timerID === 42) {
            this.timerID = null;
            timerCleared = true;
          }
        }
        render() {
          trace.push('render:' + this.state.time);
          return createElement(
            'div', null,
            createElement('h1', null, 'Hello, world!'),
            createElement('h2', { id: 'clock-time' }, '现在是 ', this.state.time, '.')
          );
        }
      }
      const clock = new Clock({});
      clock._mount(document.getElementById('clock-root'));
      const timeT0 = document.getElementById('clock-time').textContent;
      clock.tick('08:00:01');
      const timeT1 = document.getElementById('clock-time').textContent;
      clock._unmount();
      const domEmptyAfterUnmount = document.getElementById('clock-root').innerHTML === '';

      const case2 = {
        trace,
        time_t0: timeT0,
        time_t1: timeT1,
        timer_cleared: timerCleared,
        dom_empty_after_unmount: domEmptyAfterUnmount
      };

      // Case 3: Top-down unidirectional data flow to FormattedDate child
      let childPropsFrozen = false;
      function FormattedDate(props) {
        try { props.time = '99:99:99'; } catch (e) { childPropsFrozen = true; }
        return createElement('h2', { className: 'fmt-date' }, '现在是 ', props.time, '.');
      }
      class ParentClock extends Component {
        constructor(props) {
          super(props);
          this.state = { time: '12:00:00' };
        }
        render() {
          return createElement(
            'div', null,
            createElement('h1', null, 'Hello, world!'),
            createElement(FormattedDate, { time: this.state.time })
          );
        }
      }
      const pClock = new ParentClock({});
      pClock._mount(document.getElementById('flow-root'));
      const flowBefore = document.querySelector('#flow-root .fmt-date').textContent;
      pClock.setState({ time: '12:00:05' });
      const flowAfter = document.querySelector('#flow-root .fmt-date').textContent;

      const case3 = {
        flow_before: flowBefore,
        flow_after: flowAfter,
        child_props_readonly: childPropsFrozen
      };

      // Case 4: Three isolated Clock instances inside App
      const multiRoot = document.getElementById('multi-root');
      const clocks = ['01:00:00', '02:00:00', '03:00:00'].map((t, idx) => {
        const host = document.createElement('div');
        host.id = 'slot-' + idx;
        multiRoot.appendChild(host);
        const c = new ParentClock({});
        c.state = { time: t };
        c._mount(host);
        return c;
      });
      clocks[1].setState({ time: '02:00:59' });
      const case4 = {
        slot0: document.querySelector('#slot-0 .fmt-date').textContent,
        slot1: document.querySelector('#slot-1 .fmt-date').textContent,
        slot2: document.querySelector('#slot-2 .fmt-date').textContent
      };

      return { case1, case2, case3, case4 };
    };
  </script>
</body>
</html>
"""


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


def main():
    with sync_playwright() as p:
        browser = launch_browser(p)
        page = browser.new_page()
        page.set_content(HTML)
        out = page.evaluate("window.runLab()")
        browser.close()

    expected = {
        "class_and_hook_counter_state": {
            "class_after_2_clicks": "Count: 2",
            "class_after_batched_object_x3": "Count: 3",
            "class_after_batched_functional_x3": "Count: 6",
            "hook_after_3_clicks": "Count: 3",
        },
        "clock_mount_tick_unmount_lifecycle": {
            "trace": [
                "constructor",
                "render:08:00:00",
                "componentDidMount",
                "tick->setState",
                "render:08:00:01",
                "componentWillUnmount",
            ],
            "time_t0": "现在是 08:00:00.",
            "time_t1": "现在是 08:00:01.",
            "timer_cleared": True,
            "dom_empty_after_unmount": True,
        },
        "top_down_unidirectional_data_flow": {
            "flow_before": "现在是 12:00:00.",
            "flow_after": "现在是 12:00:05.",
            "child_props_readonly": True,
        },
        "isolated_multiple_clock_instances": {
            "slot0": "现在是 01:00:00.",
            "slot1": "现在是 02:00:59.",
            "slot2": "现在是 03:00:00.",
        },
    }
    actuals = {
        "class_and_hook_counter_state": out["case1"],
        "clock_mount_tick_unmount_lifecycle": out["case2"],
        "top_down_unidirectional_data_flow": out["case3"],
        "isolated_multiple_clock_instances": out["case4"],
    }
    cases = [
        {"name": name, "expected": expected[name], "actual": actuals[name], "passed": actuals[name] == expected[name]}
        for name in expected
    ]
    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-state-lab/explore-state.py

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

下载课程关联工程包:React

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

下载课程关联工程包:React

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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