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

Gam*_*007 7 profiling reactjs

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

Profiling not supported.
Profiling support requires either a development or production-profiling build of React v16.5+.
Run Code Online (Sandbox Code Playgroud)

(我的 React 版本是 16.8)我该如何解决?

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

  resolve: {
    alias: {
      'react-dom$': 'react-dom/profiling',
      'scheduler/tracing': 'scheduler/tracing-profiling',
    }
  }
};
Run Code Online (Sandbox Code Playgroud)

小智 9

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

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

<Profiler id="MyComponent" onRender={onRenderCallback}>
  <MyComponent {...props} />
</Profiler>
Run Code Online (Sandbox Code Playgroud)

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...
}
Run Code Online (Sandbox Code Playgroud)

这个 ??直接来自上面链接的 React 文档。

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

值得一提的是,配置包括你上面'react-dom/profiling',并'scheduler/tracing-profiling'在你的构建过程中需要得到这个React.Profiler工作。

希望这可以帮助你!