Profiler
一句话解释
<Profiler> 测量其子树的渲染成本——用 DevTools Profiler 或 Profiler API 优化。
用大白话说
Profiler 有两种形式:1. React DevTools Profiler——可视化工具,录制所有渲染,显示火焰图、提交时间和每次渲染的原因。无需代码更改——只需点击 Record。2. Profiler API——<Profiler id="..." onRender={callback}> 包装组件并在每次渲染后调用 onRender 并传递时间信息。用于编程式性能监控。onRender 回调接收:id、phase("mount" 或 "update")、actualDuration、baseDuration、startTime、commitTime。用它记录慢渲染或将指标发送到分析。Profiler 有开销——仅在开发或生产中的 feature flag 后使用。
示例
jsx
import { Profiler } from "react";
function onRender(id, phase, actualDuration, baseDuration) {
console.log(`${id} ${phase}: ${actualDuration}ms`);
if (actualDuration > 16) {
console.warn(`Slow render: ${id} took ${actualDuration}ms`);
}
}
function App() {
return (
<Profiler id="App" onRender={onRender}>
<Header />
<Profiler id="MainContent" onRender={onRender}>
<MainContent />
</Profiler>
<Footer />
</Profiler>
);
}Profiler 在每次提交后用时间数据调用 onRender。用它编程式地识别和记录慢渲染。
常见混淆
容易混淆的对象: React DevTools Profiler
关键区别: Profiler API(<Profiler> 组件)是编程式的——你写代码处理渲染时间数据。DevTools Profiler 是可视化的——你在浏览器扩展中点击 Record 并看到火焰图。调查用 DevTools,持续监控用 Profiler API。
相关术语
相关资源
相关课程
- React 性能
Profiler。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。