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

离线 Chromium 验证三阶段生命周期顺序、透明度定时器、父子更新与 useEffect 等价映射

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

HTML = """<!doctype html>
<html lang="zh-CN">
<head><meta charset="utf-8"><title>React Component Lifecycle Lab</title></head>
<body>
  <div id="order-root"></div>
  <div id="opacity-root"></div>
  <div id="content-root"></div>
  <div id="effect-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));
      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 === 'style' && typeof v === 'object') {
          Object.assign(el.style, v);
        } else 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;
    }

    class LifecycleComponent {
      constructor(props) {
        this.props = props || {};
        this.state = {};
        this._container = null;
      }
      _derive(props, state) {
        const Ctor = this.constructor;
        if (typeof Ctor.getDerivedStateFromProps === 'function') {
          const d = Ctor.getDerivedStateFromProps(props, state);
          if (d) return Object.assign({}, state, d);
        }
        return state;
      }
      _mount(container) {
        this._container = container;
        this.state = this._derive(this.props, this.state);
        this._commit(this.render());
        if (typeof this.componentDidMount === 'function') this.componentDidMount();
      }
      setState(next) {
        const partial = typeof next === 'function' ? next(this.state, this.props) : next;
        this._update(this.props, Object.assign({}, this.state, partial));
      }
      _receiveProps(nextProps) {
        this._update(nextProps, this.state);
      }
      _update(nextProps, nextState) {
        const derived = this._derive(nextProps, nextState);
        const allow = typeof this.shouldComponentUpdate === 'function'
          ? Boolean(this.shouldComponentUpdate(nextProps, derived))
          : true;
        const prevProps = this.props;
        const prevState = this.state;
        this.props = nextProps;
        this.state = derived;
        if (!allow) return;
        const vnode = this.render();
        const snap = typeof this.getSnapshotBeforeUpdate === 'function'
          ? this.getSnapshotBeforeUpdate(prevProps, prevState)
          : null;
        this._commit(vnode);
        if (typeof this.componentDidUpdate === 'function') {
          this.componentDidUpdate(prevProps, prevState, snap);
        }
      }
      _commit(vnode) {
        if (!this._container) return;
        this._container.innerHTML = '';
        this._container.appendChild(renderVNode(vnode));
      }
      _unmount() {
        if (typeof this.componentWillUnmount === 'function') this.componentWillUnmount();
        if (this._container) this._container.innerHTML = '';
        this._container = null;
      }
    }

    window.runLab = function () {
      // Case 1: Full Mounting / Updating (allowed & skipped) / Unmounting sequence
      const mountLog = [];
      const updateAllowLog = [];
      const updateSkipLog = [];
      const unmountLog = [];
      let activeLog = mountLog;

      class TracedComp extends LifecycleComponent {
        constructor(props) {
          super(props);
          this.state = { val: props.val };
          activeLog.push('constructor');
        }
        static getDerivedStateFromProps(props, state) {
          activeLog.push('getDerivedStateFromProps');
          return null;
        }
        shouldComponentUpdate(nextProps, nextState) {
          activeLog.push('shouldComponentUpdate');
          return nextState.val !== this.state.val;
        }
        getSnapshotBeforeUpdate(prevProps, prevState) {
          activeLog.push('getSnapshotBeforeUpdate');
          return prevState.val;
        }
        componentDidMount() { activeLog.push('componentDidMount'); }
        componentDidUpdate(prevProps, prevState, snap) { activeLog.push('componentDidUpdate'); }
        componentWillUnmount() { activeLog.push('componentWillUnmount'); }
        render() {
          activeLog.push('render');
          return createElement('div', null, String(this.state.val));
        }
      }

      const tc = new TracedComp({ val: 1 });
      tc._mount(document.getElementById('order-root'));
      activeLog = updateAllowLog;
      tc.setState({ val: 2 });
      activeLog = updateSkipLog;
      tc.setState({ val: 2 });
      activeLog = unmountLog;
      tc._unmount();

      const case1 = {
        mounting: mountLog,
        updating_allowed: updateAllowLog,
        updating_skipped: updateSkipLog,
        unmounting: unmountLog
      };

      // Case 2: Hello opacity timer step & wrap-around (< 0.1 -> 1.0) + unmount cleanup
      let timerCleaned = false;
      class HelloOpacity extends LifecycleComponent {
        constructor(props) {
          super(props);
          this.state = { opacity: 1.0 };
          this.timer = null;
        }
        componentDidMount() { this.timer = 99; }
        step() {
          let opacity = Number((this.state.opacity - 0.05).toFixed(2));
          if (opacity < 0.1) opacity = 1.0;
          this.setState({ opacity });
        }
        componentWillUnmount() {
          if (this.timer === 99) { this.timer = null; timerCleaned = true; }
        }
        render() {
          return createElement('div', { id: 'hello-op', style: { opacity: String(this.state.opacity) } },
            'Hello ', this.props.name);
        }
      }
      const ho = new HelloOpacity({ name: 'world' });
      ho._mount(document.getElementById('opacity-root'));
      const initialOp = document.getElementById('hello-op').style.opacity;
      ho.step();
      const after1Step = document.getElementById('hello-op').style.opacity;
      for (let i = 0; i < 17; i++) ho.step(); // total 18 steps -> 0.10
      const atStep18 = document.getElementById('hello-op').style.opacity;
      ho.step(); // 0.05 < 0.1 -> wraps back to 1
      const afterWrap = document.getElementById('hello-op').style.opacity;
      ho._unmount();

      const case2 = {
        initial_opacity: initialOp,
        after_1_step: after1Step,
        at_step_18: atStep18,
        after_wrap_reset: afterWrap,
        timer_cleaned_on_unmount: timerCleaned
      };

      // Case 3: Button parent driving Content child lifecycle on INCREMENT click
      const contentLogs = [];
      class Content extends LifecycleComponent {
        componentDidMount() { contentLogs.push('Component DID MOUNT!'); }
        shouldComponentUpdate(newProps) { return newProps.myNumber !== this.props.myNumber; }
        componentDidUpdate(prevProps) { contentLogs.push(`Component DID UPDATE!:${prevProps.myNumber}->${this.props.myNumber}`); }
        componentWillUnmount() { contentLogs.push('Component WILL UNMOUNT!'); }
        render() { return createElement('h3', { id: 'content-num' }, String(this.props.myNumber)); }
      }
      const contentRoot = document.getElementById('content-root');
      const btnWrap = document.createElement('div');
      const incBtn = document.createElement('button');
      incBtn.id = 'inc-btn';
      incBtn.textContent = 'INCREMENT';
      const childHost = document.createElement('div');
      btnWrap.appendChild(incBtn);
      btnWrap.appendChild(childHost);
      contentRoot.appendChild(btnWrap);

      let parentData = 0;
      const contentComp = new Content({ myNumber: parentData });
      contentComp._mount(childHost);
      incBtn.addEventListener('click', () => {
        parentData += 1;
        contentComp._receiveProps({ myNumber: parentData });
      });
      const n0 = document.getElementById('content-num').textContent;
      incBtn.click();
      const n1 = document.getElementById('content-num').textContent;
      incBtn.click();
      const n2 = document.getElementById('content-num').textContent;
      contentComp._unmount();

      const case3 = {
        numbers: [n0, n1, n2],
        content_logs: contentLogs
      };

      // Case 4: Modern useEffect equivalent of mount + update + unmount cleanup & legacy UNSAFE status
      const effectTrace = [];
      let prevDeps = null;
      let prevCleanup = null;
      function runUseEffect(setup, deps) {
        const changed = !prevDeps || deps.some((d, i) => d !== prevDeps[i]);
        if (changed) {
          if (typeof prevCleanup === 'function') prevCleanup();
          prevCleanup = setup() || null;
          prevDeps = deps.slice();
        }
      }
      function unmountEffect() {
        if (typeof prevCleanup === 'function') prevCleanup();
        prevCleanup = null;
        prevDeps = null;
      }
      function renderEffectDemo(roomId) {
        document.getElementById('effect-root').textContent = 'Room: ' + roomId;
        runUseEffect(() => {
          effectTrace.push('subscribe:' + roomId);
          return () => effectTrace.push('cleanup:' + roomId);
        }, [roomId]);
      }
      renderEffectDemo('general');
      renderEffectDemo('general'); // same dep -> no re-run
      renderEffectDemo('react');   // dep changed -> cleanup old + subscribe new
      unmountEffect();             // unmount -> cleanup latest

      const case4 = {
        effect_trace: effectTrace,
        legacy_unsafe_methods: [
          'UNSAFE_componentWillMount',
          'UNSAFE_componentWillReceiveProps',
          'UNSAFE_componentWillUpdate'
        ]
      };

      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 = {
        "full_mounting_updating_unmounting_order": {
            "mounting": ["constructor", "getDerivedStateFromProps", "render", "componentDidMount"],
            "updating_allowed": [
                "getDerivedStateFromProps",
                "shouldComponentUpdate",
                "render",
                "getSnapshotBeforeUpdate",
                "componentDidUpdate",
            ],
            "updating_skipped": ["getDerivedStateFromProps", "shouldComponentUpdate"],
            "unmounting": ["componentWillUnmount"],
        },
        "clock_and_opacity_timer_lifecycle": {
            "initial_opacity": "1",
            "after_1_step": "0.95",
            "at_step_18": "0.1",
            "after_wrap_reset": "1",
            "timer_cleaned_on_unmount": True,
        },
        "parent_button_child_content_lifecycle": {
            "numbers": ["0", "1", "2"],
            "content_logs": [
                "Component DID MOUNT!",
                "Component DID UPDATE!:0->1",
                "Component DID UPDATE!:1->2",
                "Component WILL UNMOUNT!",
            ],
        },
        "unsafe_legacy_vs_useeffect_equivalence": {
            "effect_trace": [
                "subscribe:general",
                "cleanup:general",
                "subscribe:react",
                "cleanup:react",
            ],
            "legacy_unsafe_methods": [
                "UNSAFE_componentWillMount",
                "UNSAFE_componentWillReceiveProps",
                "UNSAFE_componentWillUpdate",
            ],
        },
    }
    actuals = {
        "full_mounting_updating_unmounting_order": out["case1"],
        "clock_and_opacity_timer_lifecycle": out["case2"],
        "parent_button_child_content_lifecycle": out["case3"],
        "unsafe_legacy_vs_useeffect_equivalence": 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-component-life-cycle-lab/explore-component-life-cycle.py

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

下载课程关联工程包:React

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

下载课程关联工程包:React

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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