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

React 组件 API

核对 React 类组件完整 API(挂载/更新/卸载钩子、setState 浅合并与回调、受控表单/事件/条件/列表)以及 forceUpdate、replaceState、findDOMNode 在 React 18/19 中的演进与废弃状态。

学完这一章,你能够

  • 核对 React 类组件完整 API(挂载/更新/卸载钩子、setState 浅合并与回调、受控表单/事件/条件/列表)以及 forceUpdate、replaceState、findDOMNode 在 React 18/19 中的演进与废弃状态。

类组件生命周期 API 体系

React 类组件 API 涵盖生命周期钩子、状态管理、属性传递、事件处理与表单控制等核心能力,其中生命周期按组件存在过程划分为挂载、更新与卸载三个阶段(完整时序图与更多案例见下一章)。

挂载阶段依次调用 `constructor(props)`(初始化状态与绑定方法)、静态方法 `static getDerivedStateFromProps(props, state)`(每次 `render` 前按需从 props 派生状态,无变更返回 `null`)、`render()` 与 `componentDidMount()`(DOM 已挂载,适合发起请求或订阅)。更新阶段依次执行 `getDerivedStateFromProps`、`shouldComponentUpdate(nextProps, nextState)`(返回 `false` 可跳过本次重渲染)、`render()`、`getSnapshotBeforeUpdate(prevProps, prevState)`(DOM 提交前捕获滚动位置等快照)与 `componentDidUpdate(prevProps, prevState, snapshot)`。卸载阶段调用 `componentWillUnmount()` 清理定时器与监听器。本站离线 Chromium 实测完整链路:`count` 未变时 `shouldComponentUpdate` 返回 `false` 成功拦截无效渲染,变更后快照 `snap=2@120` 准确送达 `componentDidUpdate`,`reset=true` 通过派生状态将计数归零,卸载触发 `componentWillUnmount`。

核心交互能力:状态、属性、事件、条件、列表与受控组件

在类组件中,内部数据存于 `this.state` 并经 `setState` 变更;外部输入经 `this.props` 读取并可配合 `PropTypes`(现代工程推荐 TypeScript)校验;交互监听通过 `.bind(this)` 或类字段箭头函数确保回调内 `this` 指向组件实例。

组件渲染层常用三类基础模式:利用 `this.state.isVisible && <p>` 做条件渲染;用 `items.map(...)` 生成列表;通过将 `<input value={this.state.value} onChange={this.handleChange} />` 绑定到状态并在 `onSubmit` 中调用 `event.preventDefault()` 实现受控表单组件。本站实测输入 `React API` 并提交表单后准确捕获提交值 `React API`,切换可见性按钮使段落由显示变为隐藏,列表完整渲染 `["Item 1", "Item 2", "Item 3"]`。

setState 机制详解与旧版组件 API 在 React 18/19 中的演进

`setState(nextState, [callback])` 是类组件驱动 UI 重绘的核心方法:`nextState` 可以是浅合并到当前状态的对象或接收 `(prevState, props)` 的纯函数,可选 `callback` 在状态更新且 DOM 提交完成后触发。切忌直接修改 `this.state`(会绕过重绘且可能被后续 `setState` 覆盖);`setState` 会把更新排入队列并由 React 批量执行以优化性能,因此调用后 `this.state` 不会立即改变;除非 `shouldComponentUpdate` 返回 `false`,否则都会触发重渲染。本站实测点击 `<h2>` 计数器两次后文本更新为 `点我!点击次数为: 2`,未涉及的 `keepTag: 'stable'` 原样保留,且每次 `callback` 执行时均观测到提交后的最新状态与 DOM 文本。

针对早期资料中常见的其他类组件 API,需明确其在 React 18/19 中的当前状态:`forceUpdate()` 虽仍存在于类组件原型中并会跳过 `shouldComponentUpdate` 强制重绘(本站实测在 `shouldComponentUpdate` 恒返回 `false` 时,`setState` 未增加渲染次数,而 `forceUpdate()` 将渲染次数由 `1` 推至 `2` 并刷新为 `v2`),但官方不推荐日常使用;`replaceState()` 自 React 16 起已彻底移除,应以全量对象传给 `setState` 替代;`ReactDOM.findDOMNode()` 在 React 18 严格模式下已弃用并在 React 19 中正式移除,必须改用 `createRef`(类组件)或 `useRef`(函数组件)直接引用目标 DOM 节点。

离线 Chromium 验证类组件生命周期 API、setState 回调、受控表单与 forceUpdate 行为

含完整源码 · 346 行
展开查看收起
python
"""Offline Chromium lab for React Ch 19: component-api."""
import json
from playwright.sync_api import sync_playwright

HTML = """<!doctype html>
<html lang="zh-CN">
<head><meta charset="utf-8"><title>React Component API Lab</title></head>
<body>
  <div id="lifecycle-root"></div>
  <div id="counter-root"></div>
  <div id="form-root"></div>
  <div id="force-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' || k === 'key' || v === undefined || v === null) continue;
        if (k === 'value') el.value = String(v);
        else if (k.startsWith('on') && typeof v === 'function') {
          const ev = k === 'onChange' ? 'input' : k.slice(2).toLowerCase();
          el.addEventListener(ev, v);
        } else {
          el.setAttribute(k === 'className' ? 'class' : k, String(v));
        }
      }
      vnode.props.children.forEach(c => el.appendChild(renderVNode(c)));
      return el;
    }

    class Component {
      constructor(props) {
        this.props = props || {};
        this.state = {};
        this._queue = [];
        this._callbacks = [];
        this._batching = false;
        this._container = null;
      }
      setState(nextState, callback) {
        this._queue.push(nextState);
        if (typeof callback === 'function') this._callbacks.push(callback);
        if (!this._batching) this._flush(false);
      }
      forceUpdate(callback) {
        if (typeof callback === 'function') this._callbacks.push(callback);
        this._flush(true);
      }
      _derive(props, state) {
        const Ctor = this.constructor;
        if (typeof Ctor.getDerivedStateFromProps === 'function') {
          const derived = Ctor.getDerivedStateFromProps(props, state);
          if (derived) return Object.assign({}, state, derived);
        }
        return state;
      }
      _mount(container) {
        this._container = container;
        this.state = this._derive(this.props, this.state);
        this._commitDom();
        if (typeof this.componentDidMount === 'function') this.componentDidMount();
      }
      _receiveProps(nextProps) {
        this._runUpdate(nextProps, this.state, false);
      }
      _flush(isForce) {
        let nextState = Object.assign({}, this.state);
        for (const item of this._queue.splice(0)) {
          const partial = typeof item === 'function' ? item(nextState, this.props) : item;
          if (partial) nextState = Object.assign({}, nextState, partial);
        }
        this._runUpdate(this.props, nextState, isForce);
      }
      _runUpdate(nextProps, nextState, isForce) {
        const derivedState = this._derive(nextProps, nextState);
        const shouldRender = isForce || typeof this.shouldComponentUpdate !== 'function'
          ? true
          : Boolean(this.shouldComponentUpdate(nextProps, derivedState));
        const prevProps = this.props;
        const prevState = this.state;
        this.props = nextProps;
        this.state = derivedState;
        if (shouldRender) {
          const vnode = this.render();
          const snapshot = typeof this.getSnapshotBeforeUpdate === 'function'
            ? this.getSnapshotBeforeUpdate(prevProps, prevState)
            : null;
          this._commitDom(vnode);
          if (typeof this.componentDidUpdate === 'function') {
            this.componentDidUpdate(prevProps, prevState, snapshot);
          }
        }
        for (const cb of this._callbacks.splice(0)) cb.call(this);
      }
      _commitDom(vnode) {
        if (!this._container) return;
        const tree = vnode !== undefined ? vnode : this.render();
        this._container.innerHTML = '';
        this._container.appendChild(renderVNode(tree));
      }
      _unmount() {
        if (typeof this.componentWillUnmount === 'function') this.componentWillUnmount();
        if (this._container) this._container.innerHTML = '';
        this._container = null;
      }
    }

    window.runLab = function () {
      // Case 1: Full Component API lifecycle (getDerivedStateFromProps, SCU, getSnapshotBeforeUpdate, didUpdate, unmount)
      const log = [];
      class ApiLifecycleComp extends Component {
        constructor(props) {
          super(props);
          this.state = { count: props.initial || 0 };
          log.push('constructor');
        }
        static getDerivedStateFromProps(nextProps, prevState) {
          log.push('getDerivedStateFromProps');
          if (nextProps.reset) return { count: 0 };
          return null;
        }
        componentDidMount() { log.push('componentDidMount'); }
        shouldComponentUpdate(nextProps, nextState) {
          const changed = nextState.count !== this.state.count;
          log.push('shouldComponentUpdate:' + changed);
          return changed;
        }
        getSnapshotBeforeUpdate(prevProps, prevState) {
          log.push('getSnapshotBeforeUpdate');
          return { prevCount: prevState.count, scrollPosition: 120 };
        }
        componentDidUpdate(prevProps, prevState, snapshot) {
          log.push(`componentDidUpdate:snap=${snapshot.prevCount}@${snapshot.scrollPosition}`);
        }
        componentWillUnmount() { log.push('componentWillUnmount'); }
        render() {
          log.push('render:' + this.state.count);
          return createElement('div', { id: 'api-count' }, String(this.state.count));
        }
      }
      const lc = new ApiLifecycleComp({ initial: 2, reset: false });
      lc._mount(document.getElementById('lifecycle-root'));
      lc.setState({ count: 2 }); // unchanged -> SCU returns false -> skips render
      lc.setState({ count: 5 }); // changed -> renders + snapshot + didUpdate
      lc._receiveProps({ initial: 2, reset: true }); // derived state resets count to 0
      const countAfterReset = document.getElementById('api-count').textContent;
      lc._unmount();

      const case1 = { log, count_after_reset: countAfterReset };

      // Case 2: setState shallow merge, optional post-commit callback, and clickable h2 Counter
      const cbObserved = [];
      class Counter extends Component {
        constructor(props) {
          super(props);
          this.state = { clickCount: 0, keepTag: 'stable' };
          this.handleClick = this.handleClick.bind(this);
        }
        handleClick() {
          this.setState(
            state => ({ clickCount: state.clickCount + 1 }),
            () => cbObserved.push({
              stateCount: this.state.clickCount,
              keepTag: this.state.keepTag,
              domText: document.getElementById('counter-h2').textContent
            })
          );
        }
        render() {
          return createElement('h2', { id: 'counter-h2', onClick: this.handleClick },
            '点我!点击次数为: ', this.state.clickCount);
        }
      }
      const counter = new Counter({});
      counter._mount(document.getElementById('counter-root'));
      document.getElementById('counter-h2').click();
      document.getElementById('counter-h2').click();
      const case2 = {
        final_text: document.getElementById('counter-h2').textContent,
        callback_observations: cbObserved
      };

      // Case 3: Controlled form component + conditional visibility + list rendering
      let submittedVal = null;
      class ControlledPanel extends Component {
        constructor(props) {
          super(props);
          this.state = { value: '', isVisible: true };
        }
        handleChange = (e) => { this.setState({ value: e.target.value }); };
        handleSubmit = (e) => { e.preventDefault(); submittedVal = this.state.value; };
        toggleVisibility = () => { this.setState(prev => ({ isVisible: !prev.isVisible })); };
        render() {
          const items = ['Item 1', 'Item 2', 'Item 3'];
          return createElement(
            'div', null,
            this.state.isVisible && createElement('p', { id: 'vis-p' }, 'This is visible'),
            createElement('button', { id: 'vis-btn', onClick: this.toggleVisibility }, 'Toggle'),
            createElement('ul', { id: 'api-list' }, items.map((it, i) => createElement('li', { key: i }, it))),
            createElement('form', { id: 'ctrl-form', onSubmit: this.handleSubmit },
              createElement('input', { id: 'ctrl-input', type: 'text', value: this.state.value, onChange: this.handleChange }),
              createElement('button', { id: 'ctrl-submit', type: 'submit' }, 'Submit')
            )
          );
        }
      }
      const panel = new ControlledPanel({});
      panel._mount(document.getElementById('form-root'));
      const inputEl = document.getElementById('ctrl-input');
      inputEl.value = 'React API';
      inputEl.dispatchEvent(new Event('input', { bubbles: true }));
      document.getElementById('ctrl-form').dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }));
      const visibleBefore = document.getElementById('vis-p') !== null;
      document.getElementById('vis-btn').click();
      const visibleAfter = document.getElementById('vis-p') !== null;
      const listTexts = Array.from(document.querySelectorAll('#api-list li')).map(n => n.textContent);

      const case3 = {
        submitted_value: submittedVal,
        visible_before: visibleBefore,
        visible_after: visibleAfter,
        list_texts: listTexts
      };

      // Case 4: forceUpdate bypasses shouldComponentUpdate(false) + legacy API status in React 18/19
      let renderCount = 0;
      class ForceDemo extends Component {
        constructor(props) { super(props); this.externalVal = 'v1'; }
        shouldComponentUpdate() { return false; }
        render() {
          renderCount += 1;
          return createElement('span', { id: 'force-span' }, this.externalVal);
        }
      }
      const fd = new ForceDemo({});
      fd._mount(document.getElementById('force-root'));
      fd.setState({ dummy: 1 }); // blocked by SCU
      const countAfterBlockedSetState = renderCount;
      fd.externalVal = 'v2';
      fd.forceUpdate(); // bypasses SCU
      const case4 = {
        renders_after_blocked_setstate: countAfterBlockedSetState,
        renders_after_force_update: renderCount,
        dom_after_force_update: document.getElementById('force-span').textContent,
        legacy_api_status: {
          setState: 'supported_in_class_components',
          forceUpdate: 'supported_but_discouraged',
          replaceState: 'removed_since_react_16',
          findDOMNode: 'deprecated_in_18_removed_in_19_use_ref'
        }
      };

      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 = {
        "lifecycle_and_derived_snapshot_api": {
            "log": [
                "constructor",
                "getDerivedStateFromProps",
                "render:2",
                "componentDidMount",
                "getDerivedStateFromProps",
                "shouldComponentUpdate:false",
                "getDerivedStateFromProps",
                "shouldComponentUpdate:true",
                "render:5",
                "getSnapshotBeforeUpdate",
                "componentDidUpdate:snap=2@120",
                "getDerivedStateFromProps",
                "shouldComponentUpdate:true",
                "render:0",
                "getSnapshotBeforeUpdate",
                "componentDidUpdate:snap=5@120",
                "componentWillUnmount",
            ],
            "count_after_reset": "0",
        },
        "setstate_merge_batch_and_callback": {
            "final_text": "点我!点击次数为: 2",
            "callback_observations": [
                {"stateCount": 1, "keepTag": "stable", "domText": "点我!点击次数为: 1"},
                {"stateCount": 2, "keepTag": "stable", "domText": "点我!点击次数为: 2"},
            ],
        },
        "controlled_form_and_conditional_list": {
            "submitted_value": "React API",
            "visible_before": True,
            "visible_after": False,
            "list_texts": ["Item 1", "Item 2", "Item 3"],
        },
        "legacy_api_status_vs_react18_19": {
            "renders_after_blocked_setstate": 1,
            "renders_after_force_update": 2,
            "dom_after_force_update": "v2",
            "legacy_api_status": {
                "setState": "supported_in_class_components",
                "forceUpdate": "supported_but_discouraged",
                "replaceState": "removed_since_react_16",
                "findDOMNode": "deprecated_in_18_removed_in_19_use_ref",
            },
        },
    }
    actuals = {
        "lifecycle_and_derived_snapshot_api": out["case1"],
        "setstate_merge_batch_and_callback": out["case2"],
        "controlled_form_and_conditional_list": out["case3"],
        "legacy_api_status_vs_react18_19": 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()
核对 getDerivedStateFromProps/SCU/getSnapshotBeforeUpdate/componentDidUpdate 顺序、setState 浅合并与提交后回调、受控输入提交与显隐切换,以及 forceUpdate 绕过 SCU 与旧版 API 废弃状态。

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

本地运行

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

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

本章附件与实例包

下载课程关联工程包:React

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

下载课程关联工程包:React

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

常见错误与边界检查

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

技术规范与官方资料

练习与参考解答

查看参考解答

`setState` 的 `callback` 会在本批状态合并并完成 DOM 重绘提交之后执行,此时可读取最新 `this.state` 与更新后的 DOM;`replaceState` 自 React 16 起已移除,`findDOMNode` 在 React 18 弃用并于 React 19 移除,获取真实 DOM 应统一改用 `createRef` 或 `useRef`。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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