在 Chrome DevTools 中分析 React 应用程序 - 不支持性能分析



当我尝试分析我的应用程序的生产版本时,在Chrome DevTools的Profile选项卡中,我收到以下消息:

Profiling not supported.
Profiling support requires either a development or production-profiling build of React v16.5+.

(我的 React 版本是 16.8( 我该如何解决这个问题?

我正在使用 Webpack4,按照官方 React 文档的建议将其添加到我的配置文件中没有帮助:

resolve: {
alias: {
'react-dom$': 'react-dom/profiling',
'scheduler/tracing': 'scheduler/tracing-profiling',
}
}
};

默认情况下,React 在生产构建中不包含分析,您需要使用 Profiler API 添加它。

探查器 API 提供了一个组件,该组件将 id(字符串(和 onRender 回调作为参数。你可以用这个组件包装 React 树的任何部分,并从中获取分析信息,尽管它在 DevTools 中不可用,因此不会有漂亮的火焰图。它看起来像这样:

<Profiler id="MyComponent" onRender={onRenderCallback}>
<MyComponent {...props} />
</Profiler>

onRender回调确实提供了一些简洁的信息,但您可以将其发送到 API 端点:

function onRenderCallback(
id, // the "id" prop of the Profiler tree that has just committed
phase, // either "mount" (if the tree just mounted) or "update" (if it re-rendered)
actualDuration, // time spent rendering the committed update
baseDuration, // estimated time to render the entire subtree without memoization
startTime, // when React began rendering this update
commitTime, // when React committed this update
interactions // the Set of interactions belonging to this update
) {
// Aggregate or log render timings...
}

这☝️直接来自上面链接的 React 文档。

请记住,您添加的任何组件都会增加 CPU 和内存开销,因此您实际上应该只在需要时使用 React.Profiler。理想情况下,您应该在开发模式下分析组件并查找瓶颈。

值得注意的是,在构建过程中,您需要上面包含的用于'react-dom/profiling''scheduler/tracing-profiling'的配置才能使此 React.Profiler 正常工作。

希望这对您有所帮助!

最新更新