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

React 组件状态

核对组件私有 State 概念、类组件 setState 与函数组件 useState 状态管理、Clock 挂载/卸载定时器生命周期,以及自顶向下单向数据流与实例隔离。

学完这一章,你能够

  • 核对组件私有 State 概念、类组件 setState 与函数组件 useState 状态管理、Clock 挂载/卸载定时器生命周期,以及自顶向下单向数据流与实例隔离。

组件状态概念与类组件 / Hook 计数器实现

State(状态)是归属于组件内部的私有动态数据。React 将组件视作状态机:用户交互或异步事件触发状态变更后,React 自动根据新状态重新渲染界面,开发者无需手动操作 DOM。类组件在 `constructor(props)` 中先调用 `super(props)` 再初始化 `this.state`,并调用 `this.setState(...)` 驱动更新;函数组件则通过 React Hook(最常用的是 `useState`)拥有状态能力。

以计数器 `Counter` 为例,类组件在构造函数初始化 `this.state = { count: 0 }` 并用 `setState` 递增,函数组件则通过 `const [count, setCount] = useState(0)` 声明状态与更新函数,并在入口文件用 `createRoot` 挂载。需要特别留意 React 的批量更新机制:当同一批次中多次基于旧值累加时,传入函数式更新器 `prev => ({ count: prev.count + 1 })` 才能保证每次都读取最新队列值。本站离线 Chromium 实测类组件点击 2 次得到 `Count: 2`,同批次调用 3 次对象形式 `setState({ count: this.state.count + 1 })` 仅合并为 `Count: 3`,而同批次调用 3 次函数式更新器精确递进至 `Count: 6`;函数组件 `useState` 点击 3 次稳定输出 `Count: 3`。

为 Clock 状态组件添加挂载与卸载生命周期

先将时间数据收归 `Clock` 自身的 `this.state = { date: new Date() }`,再为组件加上生命周期方法以管理定时器资源:组件首次插入 DOM 称为“挂载(Mounting)”,适合在 `componentDidMount()` 中启动每秒执行一次 `tick()` 的定时器并保存句柄 `this.timerID`;组件从 DOM 移除称为“卸载(Unmounting)”,必须在 `componentWillUnmount()` 中调用 `clearInterval(this.timerID)` 释放定时器以防内存泄漏。

完整执行链路分为五步:1. `<Clock />` 传入根节点渲染时,React 先调用 `Clock` 构造函数初始化 `this.state`;2. 调用 `render()` 计算输出并更新 DOM;3. 输出插入 DOM 后触发 `componentDidMount()` 注册定时器;4. 定时器周期调用 `tick()`,其内部通过 `this.setState(...)` 通知 React 状态变更并再次执行 `render()` 刷新时间;5. 组件移出 DOM 时触发 `componentWillUnmount()` 清除定时器。本站实测精确捕获顺序 `["constructor", "render:08:00:00", "componentDidMount", "tick->setState", "render:08:00:01", "componentWillUnmount"]`,卸载后 `timer_cleared=true` 且容器清空。

自顶向下单向数据流与多实例状态隔离

状态具有局部性与封装性:父组件与子组件都不必关心其他组件是有状态还是无状态,也不必关心其由函数还是类实现。`Clock` 可以把自身的 `this.state.date` 作为普通属性传递给子组件 `<FormattedDate date={this.state.date} />`,子组件只读取只读 `props.date` 而无从得知其来源。这种数据只能自顶向下影响子树、不能反向篡改父状态的模式称为“单向数据流”。本站实测父时钟状态由 `12:00:00` 变为 `12:00:05` 时子组件自动同步刷新,且子组件 `props` 冻结只读。

每个组件实例的状态完全独立隔离。在 `App` 中并排渲染三个 `<Clock />` 时,每个实例都会建立自己的定时器并独立更新;且有状态与无状态属于可随需求演进的内部实现细节,二者可以自由相互嵌套。本站实测三个并发时钟实例(`01:00:00`、`02:00:00`、`03:00:00`)仅更新第二个实例至 `02:00:59`,其余两个实例 DOM 输出保持原值不受干扰。

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

含完整源码 · 326 行
展开查看收起
python
"""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()
核对类组件对象与函数式批处理更新差异(3 vs 6)、Hook 计数器点击递增、Clock 六步生命周期追踪与定时器清理、单向数据流及三时钟实例隔离。

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

本地运行

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

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

本章附件与实例包

下载课程关联工程包:React

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

下载课程关联工程包:React

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

常见错误与边界检查

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

技术规范与官方资料

练习与参考解答

查看参考解答

React 会批量合并同一事件中的多次状态更新;对象写法三次读取的都是同一份旧 `this.state.count`,合并后仅加 1,而函数式更新器每次接收上一条更新后的最新 `prev`,因此能准确累加 3。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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