首页 > 解决方案 > 在 Chrome DevTools 中分析 React 应用程序 - 不支持分析

问题描述

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

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',
    }
  }
};

标签: reactjsprofiling

解决方案


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

Profiler 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 工作所必需的。

希望这可以帮助你!


推荐阅读