react源码如何处理生命周期
React 生命周期处理机制
React 的生命周期处理主要分为三个阶段:挂载(Mounting)、更新(Updating)和卸载(Unmounting)。React 内部通过协调算法(Reconciliation)和 Fiber 架构管理这些生命周期。
挂载阶段(Mounting)
组件实例被创建并插入 DOM 时触发:
constructor:初始化状态和绑定方法。static getDerivedStateFromProps:在渲染前根据新的 props 计算状态。render:生成虚拟 DOM。componentDidMount:DOM 挂载完成后执行,适合发起网络请求或订阅事件。
class Example extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
static getDerivedStateFromProps(nextProps, prevState) {
return null; // 返回更新的状态或 null
}
componentDidMount() {
console.log('Component mounted');
}
render() {
return <div>{this.state.count}</div>;
}
}
更新阶段(Updating)
props 或 state 变化时触发:

static getDerivedStateFromProps:与挂载阶段相同。shouldComponentUpdate:返回布尔值决定是否重新渲染,默认返回true。render:生成新的虚拟 DOM。getSnapshotBeforeUpdate:DOM 更新前捕获信息(如滚动位置)。componentDidUpdate:DOM 更新后执行,可操作 DOM 或发起请求。
shouldComponentUpdate(nextProps, nextState) {
return nextState.count !== this.state.count;
}
getSnapshotBeforeUpdate(prevProps, prevState) {
return { scrollPosition: window.scrollY };
}
componentDidUpdate(prevProps, prevState, snapshot) {
if (snapshot.scrollPosition !== window.scrollY) {
window.scrollTo(0, snapshot.scrollPosition);
}
}
卸载阶段(Unmounting)
组件从 DOM 中移除时触发:
componentWillUnmount:清理定时器、取消订阅等。
componentWillUnmount() {
clearInterval(this.timerID);
}
Fiber 架构下的生命周期
React 16 引入 Fiber 架构后,生命周期分为三个阶段:

- Render 阶段:可中断,包含
getDerivedStateFromProps和shouldComponentUpdate。 - Pre-commit 阶段:不可中断,包含
getSnapshotBeforeUpdate。 - Commit 阶段:同步执行,包含
componentDidMount和componentDidUpdate。
废弃的生命周期方法
React 17+ 废弃以下方法:
componentWillMountcomponentWillReceivePropscomponentWillUpdate
替代方案:
- 使用
static getDerivedStateFromProps替代componentWillReceiveProps。 - 使用
getSnapshotBeforeUpdate替代componentWillUpdate。
函数组件与 Hooks
函数组件通过 Hooks 模拟生命周期:
useEffect:组合componentDidMount、componentDidUpdate和componentWillUnmount。useMemo/useCallback:优化性能,类似shouldComponentUpdate。
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
console.log('Component mounted or updated');
return () => console.log('Component will unmount');
}, [count]); // 依赖数组控制触发条件
}






