组件 Lifecycle
Mounting, 更新, and unmounting phases, and 如何 Hook 映射到 旧 lifecycle 方法.
你将学到
- three phases: mount, 更新, and unmount
- 如何 useEffect 映射到 lifecycle phases
- dependency 数组 as lifecycle control
- Migrating mental models 从类 lifecycle 方法到 Hook
概念讲解
The Three Phases
每个React component goes through three lifecycle phases. Mounting is when the component is added to the DOM for the first time. Updating is when the component re-renders due to changed props or state. Unmounting is when the component is removed from the DOM. Understanding these phases helps you know when effects run, when to set up and tear down resources, and when to optimize.
useEffect as Lifecycle
In the hooks era, useEffect handles all three phases. An effect with an empty dependency array [] runs once on mount — this replaces componentDidMount. An effect with dependencies [, b] runs on mount and whenever ` or b change — this replaces componentDidUpdate. The cleanup function returned from an effect runs before the next effect and on unmount — this replaces componentWillUnmount`. One hook replaces three separate lifecycle methods.
The Mount-Update-Unmount Cycle
When a component mounts, React runs all effects in order. When a dependency changes, React first runs the cleanup of the previous effect, then runs the new effect. When the component unmounts, React runs the final cleanup. This cleanup-before-effect ordering ensures no stale listeners or timers linger. Visualize it as: mount → effect → [deps change → cleanup → effect]* → cleanup → unmount.
From Classes to Hooks
If you are migrating from class components, the mental shift is significant. Instead of thinking "什么应该 I 做当组件 mounts," think "什么做 I 需要到 synchronize 使用这些值." The effect runs after render to synchronize the component with some external system (the DOM, a subscription, a timer). The dependency array declares which values the synchronization depends on. This declarative approach is more robust than the imperative lifecycle methods.
Strict Mode Double Invocation
In development, React Strict Mode intentionally double-invokes effects (mount, unmount, mount) to help you find bugs in cleanup logic. This is not a bug — it is a feature. If your effect breaks under double invocation, your cleanup is incomplete. Ensure your cleanup fully reverses the effect so that running the effect twice produces the same result as running it once.
示例代码
import { useState, useEffect, useRef } from "react";
function LifecycleDemo({ userId }) {
const [data, setData] = useState(null);
const renderCount = useRef(0);
// Track renders — runs after every render (no dependency array).
useEffect(() => {
renderCount.current += 1;
console.log(`Render #${renderCount.current}`);
});
// Mount + update when userId changes — replaces didMount + didUpdate.
useEffect(() => {
console.log(`Fetching data for user ${userId}`);
let cancelled = false;
fetch(`/api/users/${userId}`)
.then(res => res.json())
.then(json => { if (!cancelled) setData(json); });
// Cleanup: prevents setting state after unmount or userId change.
return () => { cancelled = true; };
}, [userId]);
// Unmount only — empty deps, cleanup runs on unmount.
useEffect(() => {
console.log("Component mounted");
return () => console.log("Component unmounting");
}, []);
return <div>{data ? data.name : "Loading..."}</div>;
}
Three 副作用 demonstrate lifecycle: one 运行每个渲染, one 运行 on mount and 当 userId 更改 (使用 cleanup 到 prevent stale 更新), and one logs mount/unmount.
动手试一试
- Code Diff
Compare 类 lifecycle 方法到 它们的 Hook equivalents.
- JSON Formatter
Inspect 数据获取期间 mount/更新 lifecycle.
常见错误
错误写法
Treating useEffect 如 componentDidMount 仅
正确做法
useEffect 是更多 than mount Hook. 它的 dependency 数组 controls 当它 re-运行. Think in terms 的 synchronizing 使用值, 不 lifecycle 事件. 包含所有 used 值 in dependency 数组.
错误写法
Forgetting cleanup for 异步操作 in 副作用
正确做法
如果你 获取数据 in 副作用, use cancelled flag or AbortController in cleanup. 不使用它, 副作用可能 try 到更新状态之后组件 unmounts, causing 警告 or 错误.
练习 组件 Lifecycle
1 个练习
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。