react16源码中如何处理生命周期
React 16 生命周期处理机制
React 16 引入了 Fiber 架构,对生命周期进行了重大调整。以下是核心处理逻辑:
挂载阶段
constructor:初始化 state 和绑定方法static getDerivedStateFromProps:在渲染前同步更新 staterender:生成虚拟 DOMcomponentDidMount:完成 DOM 挂载后触发
更新阶段
static getDerivedStateFromProps:props 变化时触发shouldComponentUpdate:返回布尔值决定是否更新render:生成新虚拟 DOMgetSnapshotBeforeUpdate:DOM 更新前捕获信息componentDidUpdate:完成 DOM 更新后触发
卸载阶段
componentWillUnmount:清理定时器/订阅等
废弃的生命周期方法
React 16.3 标记以下方法为不安全:
componentWillMountcomponentWillReceivePropscomponentWillUpdate
这些方法在异步渲染模式下可能导致问题,建议使用新替代方案:
getDerivedStateFromProps替代componentWillReceivePropsgetSnapshotBeforeUpdate处理更新前逻辑
错误边界处理
新增生命周期:
static getDerivedStateFromError:捕获子组件错误componentDidCatch:记录错误信息
示例代码实现:
class ErrorBoundary extends React.Component {
state = { hasError: false };
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, info) {
logErrorToService(error, info);
}
render() {
return this.state.hasError
? <FallbackUI />
: this.props.children;
}
}
Fiber 架构的影响
新的协调算法使得:
- 生命周期可能被中断和重启
- 渲染过程分为多个优先级阶段
- 异步更新可能延迟某些生命周期执行
这种变化要求开发者避免在生命周期中执行副作用,推荐将数据获取等操作移至 componentDidMount 或 componentDidUpdate。







