Skip to content

Lifecycle

一句话解释

Lifecycle refers 到序列的 phases 组件 goes 通过: mounting (添加到 DOM), 更新 (状态/Props 更改), and unmounting (移除从 DOM).

用大白话说

每个React component goes through a lifecycle: it is mounted (created and added to the DOM), updated (re-rendered when state or props change), and unmounted (removed from the DOM).

In class components, lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount let you run code at each phase. In function components, the useEffect Hook covers all of them: the setup function runs on mount and updates, and the returned cleanup function runs on unmount and before each re-effect.

Understanding the lifecycle is crucial for side effects: fetch data on mount, subscribe on mount and unsubscribe on unmount, clean up timers on unmount. Forgetting cleanup leads to memory leaks and stale state updates.

示例

jsx
useEffect(() => {
  // Mount + update: subscribe
  const sub = api.subscribe(handler);
  return () => {
    // Unmount / before next effect: unsubscribe
    sub.unsubscribe();
  };
}, []); // [] = run only on mount, cleanup on unmount

副作用 subscribes on mount. cleanup 函数 unsubscribes 当组件 unmounts, preventing memory leaks.

相关术语

相关资源

相关课程

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回术语表