React 组件生命周期
核对 Mounting/Updating/Unmounting 三阶段完整钩子顺序、Clock 与透明度定时器及父子更新实测、旧版 UNSAFE_ 钩子弃用状态,以及现代 useEffect 等价映射。
学完这一章,你能够
- 核对 Mounting/Updating/Unmounting 三阶段完整钩子顺序、Clock 与透明度定时器及父子更新实测、旧版 UNSAFE_ 钩子弃用状态,以及现代 useEffect 等价映射。
生命周期三阶段与挂载 / 更新 / 卸载调用顺序
React 类组件的完整生命周期划分为三个阶段:Mounting(挂载,实例创建并插入真实 DOM)、Updating(更新,因新 props、`setState()` 或 `forceUpdate()` 触发重新渲染)以及 Unmounting(卸载,组件从真实 DOM 移除)。来源生命周期流程图清晰划分了上方的 Render 阶段与下方的 Commit 阶段(该缓存参考图已完成像素核查并仅留存私有证据)。
挂载阶段按固定顺序依次调用:`constructor()`(挂载前初始化状态与绑定方法)→ `static getDerivedStateFromProps()`(每次 `render` 前调用)→ `render()`(类组件中唯一必须实现的方法)→ `componentDidMount()`(插入 DOM 树后立即执行,适合启动定时器、网络请求或 DOM 订阅)。除 `render()` 外其余方法均按需实现,细节可对照官方组件文档。
每当组件的 `props` 或 `state` 变化时进入更新阶段,依次调用:`getDerivedStateFromProps()` → `shouldComponentUpdate()`(返回 `false` 则中止后续渲染与提交)→ `render()` → `getSnapshotBeforeUpdate()`(DOM 提交前读取旧布局信息)→ `componentDidUpdate()`(更新提交后立即调用)。组件从 DOM 移除进入卸载阶段时,直接调用 `componentWillUnmount()` 释放资源。本站离线 Chromium 实测精确录得挂载序列 `["constructor", "getDerivedStateFromProps", "render", "componentDidMount"]`、允许更新序列 `["getDerivedStateFromProps", "shouldComponentUpdate", "render", "getSnapshotBeforeUpdate", "componentDidUpdate"]`、被 `shouldComponentUpdate` 拦截时仅执行前两步,卸载序列为 `["componentWillUnmount"]`。
生命周期实战:时钟、透明度动画与父子组件联动
定时器是生命周期的典型应用场景:`Clock` 在 `componentDidMount` 启动每秒计时器并在 `componentWillUnmount` 中清除(实战应挂载到专用 `<div id="root">`,不要直接挂载到 `document.body` 以免被浏览器插件或脚本污染);`Hello` 组件则在挂载后每隔 100 毫秒将 `opacity` 递减 `0.05`,降至小于 `0.1` 时重置为 `1.0`(实际工程务必补充 `componentWillUnmount` 清理 `this.timer` 以防止组件卸载后持续调用 `setState` 造成泄漏)。本站实测 `Hello` 透明度从 `1` 步进至 `0.95`,第 18 步达 `0.1`,下一步准确回绕重置为 `1`,卸载时定时器清理标记为 `true`。
在父子嵌套场景中,父组件 `Button` 维护 `state.data` 并通过 `setNewNumber` 递增,把最新数值作为 `myNumber` 传给子组件 `Content`。每次点击 `INCREMENT` 按钮都会触发 `Content` 的更新生命周期。本站实测连续点击两次后 `<h3>` 依次显示 `0` → `1` → `2`,`Content` 完整记录 `Component DID MOUNT!`、`Component DID UPDATE!:0->1`、`Component DID UPDATE!:1->2` 以及卸载时的 `Component WILL UNMOUNT!`。
旧版 UNSAFE_ 钩子与现代函数组件 useEffect 等价关系
历史版本中的 `componentWillMount`、`componentWillReceiveProps` 与 `componentWillUpdate` 因与并发渲染不兼容,已更名为 `UNSAFE_componentWillMount`、`UNSAFE_componentWillReceiveProps` 与 `UNSAFE_componentWillUpdate` 并被官方标记为遗留废弃接口,新代码切勿使用。在现代 React 18/19 函数组件中,挂载、依赖更新与卸载清理统一由 `useEffect(() => { /* 挂载及依赖变更副作用 */; return () => { /* 下次执行前及卸载清理 */; }, [deps])` 表达。本站离线实测 `roomId` 从 `general`(重复渲染同值不重跑)切换为 `react` 再卸载,精确录得 `["subscribe:general", "cleanup:general", "subscribe:react", "cleanup:react"]`,完整对应类组件的挂载、更新清理与卸载语义。
离线 Chromium 验证三阶段生命周期顺序、透明度定时器、父子更新与 useEffect 等价映射
"""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()
- 核对挂载/允许更新/跳过更新/卸载精确钩子列表、透明度 1->0.95->0.1->1 回绕与定时器清理、Button/Content 点击更新日志,以及 useEffect 订阅与清理序列。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:4cd060fa16258c59d485cf2e4510e4d85cabff75eb06c55ac98f54dbbe680c5e
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:d07345e455b0f3db6ebba62352182f6e7adfaf1b7331eeae58eb87b492ee6bc6
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
类组件挂载、更新和卸载三阶段的核心钩子顺序是什么?在现代函数组件中如何用 `useEffect` 等价实现 `componentDidMount`、`componentDidUpdate` 与 `componentWillUnmount`?
展开参考解答
挂载为 `constructor → getDerivedStateFromProps → render → componentDidMount`;更新为 `getDerivedStateFromProps → shouldComponentUpdate → render → getSnapshotBeforeUpdate → componentDidUpdate`;卸载为 `componentWillUnmount`。函数组件通过 `useEffect(() => { setup(); return () => cleanup(); }, [deps])` 统一表达:空依赖数组 `[]` 对应挂载与卸载,传入依赖项则在依赖变化前先执行清理再重新执行副作用。