<Profiler> 让你以编程方式测量 React 树的渲染性能。
<Profiler id="App" onRender={onRender}>
<App />
</Profiler>参考
🌐 Reference
<Profiler>
将组件树封装在 <Profiler> 中以测量其渲染性能。
🌐 Wrap a component tree in a <Profiler> to measure its rendering performance.
<Profiler id="App" onRender={onRender}>
<App />
</Profiler>属性
🌐 Props
id:标识你正在测量的 UI 部分的字符串。onRender:一个onRender回调,React 会在配置文件树中的组件每次更新时调用它。它会接收关于渲染内容以及所花费时间的信息。
注意事项
🌐 Caveats
- 性能分析会增加一些额外的开销,所以**在生产构建中默认是禁用的。**要选择在生产环境中进行性能分析,你需要启用带有性能分析功能的特殊生产构建。
onRender 回调
🌐 onRender callback
React 会使用有关渲染内容的信息来调用你的 onRender 回调。
🌐 React will call your onRender callback with information about what was rendered.
function onRender(id, phase, actualDuration, baseDuration, startTime, commitTime) {
// Aggregate or log render timings...
}参数
🌐 Parameters
id:刚提交的<Profiler>树的id字符串属性。如果你使用多个分析器,这可以让你识别出树的哪一部分被提交了。phase:"mount"、"update"或"nested-update"。这可以让你知道这个树是第一次被挂载,还是由于 props、state 或 Hooks 的变化而重新渲染。actualDuration:在当前更新中渲染<Profiler>及其子孙节点所花费的毫秒数。这表明子树对记忆化的使用情况(例如memo和useMemo)。理想情况下,在初始挂载后,该值应显著下降,因为许多子孙节点只会在其特定 props 改变时才需要重新渲染。baseDuration:估算重新渲染整个<Profiler>子树而不进行任何优化所需时间的毫秒数。它通过将树中每个组件最近的渲染持续时间相加计算得出。该值估算了渲染的最坏情况成本(例如,初始挂载或没有使用 memoization 的树)。将actualDuration与其进行比较以查看 memoization 是否有效。startTime:React 开始渲染当前更新时的数字时间戳。commitTime:React 提交当前更新时的数字时间戳。此值在一次提交中的所有分析器之间共享,使它们在需要时可以被分组。
用法
🌐 Usage
以编程方式测量渲染性能
🌐 Measuring rendering performance programmatically
将 <Profiler> 组件封装在 React 树周围,以测量其渲染性能。
🌐 Wrap the <Profiler> component around a React tree to measure its rendering performance.
<App>
<Profiler id="Sidebar" onRender={onRender}>
<Sidebar />
</Profiler>
<PageContent />
</App>它需要两个属性:一个 id(字符串)和一个 onRender 回调函数(函数),当树中的组件“提交”更新时,React 会调用该回调函数。
🌐 It requires two props: an id (string) and an onRender callback (function) which React calls any time a component within the tree “commits” an update.
测量应用的不同部分
🌐 Measuring different parts of the application
你可以使用多个 <Profiler> 组件来测量应用的不同部分:
🌐 You can use multiple <Profiler> components to measure different parts of your application:
<App>
<Profiler id="Sidebar" onRender={onRender}>
<Sidebar />
</Profiler>
<Profiler id="Content" onRender={onRender}>
<Content />
</Profiler>
</App>你也可以嵌套 <Profiler> 组件:
🌐 You can also nest <Profiler> components:
<App>
<Profiler id="Sidebar" onRender={onRender}>
<Sidebar />
</Profiler>
<Profiler id="Content" onRender={onRender}>
<Content>
<Profiler id="Editor" onRender={onRender}>
<Editor />
</Profiler>
<Preview />
</Content>
</Profiler>
</App>虽然 <Profiler> 是一个轻量级组件,但应仅在必要时使用。每次使用都会为应用增加一些 CPU 和内存开销。
🌐 Although <Profiler> is a lightweight component, it should be used only when necessary. Each use adds some CPU and memory overhead to an application.