类组件的生命周期分三阶段:挂载(constructor → render → componentDidMount)、更新(shouldComponentUpdate → render → componentDidUpdate)、卸载(componentWillUnmount)。函数组件没有这些钩子,而是用 hooks 表达同样的时机:useEffect 的依赖数组决定它何时执行,空数组对应挂载后,有依赖对应更新后,返回的清理函数对应卸载前。
两者并非一一对应,思路要切换:类组件是按时间点写代码,函数组件是按数据依赖写代码。比如每秒自增的定时器,类组件在 componentDidMount 里启动、componentWillUnmount 里清除,函数组件则是一个 useEffect 里既开定时器又 return 清理函数,依赖为空即可。
import { useState, useEffect } from 'react'; function Timer() { const [count, setCount] = useState(0); useEffect(() => { const timer = setInterval(() => setCount((c) => c + 1), 1000); return () => clearInterval(timer); // 卸载前清理,等价 componentWillUnmount }, []); // 空数组:只挂载时执行一次 return <h3>已运行 {count} 秒</h3>; }