react性能监控根据工具_高性能React:3个新工具可加快您的应用程序

react性能监控根据工具

by Ben Edelstein

通过本·爱德斯坦

高性能React:3个新工具可加快您的应用程序 (High Performance React: 3 New Tools to Speed Up Your Apps)

React is usually pretty fast, but it’s easy to make small mistakes that lead to performance issues. Slow component mounts, deep component trees, and unnecessary render cycles can quickly add up to an app that feels slow.

React通常非常快,但是容易犯一些小错误而导致性能问题。 缓慢的组件安装,较深的组件树和不必要的渲染周期可以Swift使感觉缓慢的应用程序加起来。

Luckily there are lots of tools, some even built in to React, that help with diagnosing performance issues. In this post I’ll highlight tools and techniques for making React apps fast. Each section also has an interactive, and (hopefully) fun demo!

幸运的是,有很多工具,甚至是React内置的工具,都可以帮助诊断性能问题。 在这篇文章中,我将重点介绍使React应用程序快速运行的工具和技术。 每个部分都有一个交互式的(希望)有趣的演示!

工具1:效果时间表 (Tool 1: The Performance Timeline)

React 15.4.0 introduced a new performance timeline feature that lets you see exactly when components get mounted, updated, and unmounted. It also lets you visualize component lifecycles in relation to each other.

React 15.4.0引入了新的性能时间轴功能,可让您确切地看到何时安装,更新和卸载组件。 它还使您可以可视化彼此之间的组件生命周期。

Note: For now, this feature only works in Chrome, Edge, and IE, since it leverages the User Timing API which has yet to be implemented in all browsers.

注意:目前,此功能仅适用于Chrome,Edge和IE,因为它利用了尚未在所有浏览器中实现的用户计时API。

这个怎么运作 (How it works)
  1. Open your app and append the query param: react_perf. For example, http://localhost:3000?react_perf

    打开您的应用,然后附加查询参数: react_perf 。 例如, http://localhost:3000?react_perf

  2. Open the Chrome DevTools Performance tab and press Record.

    打开Chrome DevTools 性能选项卡,然后按记录

  3. Perform the actions that you want to analyze.

    执行您要分析的动作。
  4. Stop recording.

    停止录音。
  5. Inspect the visualization under User Timing.

    在“ 用户计时”下检查可视化

了解输出 (Understanding the output)

Each colored bar shows time that a component is doing “work”. Since JavaScript is single-threaded, whenever a component is mounting or rendering, it’s hogging the main thread and preventing other code from running.

每个彩色条显示组件执行“工作”的时间。 由于JavaScript是单线程的,因此无论何时安装或渲染组件,它都会占用主线程并阻止其他代码运行。

The text in brackets like [update] describes which part of the component lifecycle is taking place. The timeline breaks down each step, so you can see fine-grained timings on methods like [componentDidMount] [componentWillReceiveProps] [ctor] (constructor) and [render].

括号中的文本(如[update]描述了组件生命周期的哪一部分正在发生。 时间线分解了每个步骤,因此您可以在[componentDidMount] [componentWillReceiveProps] [ctor] (构造函数)和[render].等方法上看到细粒度的计时[render].

Bars that are stacked represent component trees. While it is typical to have fairly deep component trees in React, if you are optimizing a component that is mounted frequently, it can help to reduce the number of wrapper components since each adds a small performance and memory penalty.

堆叠的条表示组件树。 尽管在React中通常具有相当深的组件树,但是如果您要优化频繁安装的组件,则可以帮助减少包装器组件的数量,因为每个包装器都会增加性能和内存损失。

One caveat here is that the timing numbers in the timeline are for the development build of React, which is much slower than prod. In fact, the performance timeline itself even slows down your app. While these numbers shouldn’t be considered representative of real-world performance, the relative timings between different components are accurate. Also, whether or not a component updates at all is not dependent on a prod build.

需要注意的是,时间轴中的时序号是用于React的开发版本的,它比prod慢得多。 实际上,性能时间表甚至会减慢您的应用速度。 尽管这些数字不应被视为代表实际性能,但不同组件之间的相对时间是准确的。 而且,组件是否完全不依赖于产品构建。

演示1 (Demo 1)

For fun, I rigged the TodoMVC app to have some serious performance problems. You can try it out here.

为了娱乐,我操纵了TodoMVC应用程序出现了一些严重的性能问题。 您可以在这里尝试

To see the timeline, open the Chrome dev tools, go to the “Performance” tab, and click Record. Then add some TODOs in the app, stop the recording, and inspect the timeline. See if you can spot which components are causing the performance problems :)

要查看时间轴,请打开Chrome开发工具,转到“性能”标签,然后单击“记录”。 然后在应用程序中添加一些待办事项,停止录制,并检查时间线。 看看是否可以找出导致性能问题的组件:)

工具2:您为什么更新 (Tool 2: why-did-you-update)

One of the most common issues that affects performance in React is unnecessary render cycles. By default, React components will re-render whenever their parent renders, even if their props didn’t change.

影响React性能的最常见问题之一是不必要的渲染周期。 默认情况下,React组件将在其父对象渲染时重新渲染,即使它们的道具没有改变。

For example, if I have a simple component like this:

例如,如果我有一个像这样的简单组件:

class DumbComponent extends Component {  render() {    return <div> {this.props.value} </div>;  }}

With a parent component like this:

使用这样的父组件:

class Parent extends Component {  render() {    return <div>      <DumbComponent value={3} />    </div>;  }}

Whenever the parent component renders, DumbComponent will re-render, despite its props not changing.

无论父组件何时渲染, DumbComponent都会重新渲染,尽管其道具没有改变。

Generally, if render runs, and there were no changes to the virtual DOM, it is a wasted render cycle since the render method should be pure and not have any side effects. In a large-scale React app, it can be tricky to detect places where this happens, but luckily, there’s a tool that can help!

通常,如果运行render ,并且虚拟DOM没有任何更改,则这是浪费的渲染周期,因为render方法应该是纯净的且没有任何副作用。 在大型React应用程序中,检测发生这种情况的位置可能很棘手,但是幸运的是,有一个工具可以提供帮助!

使用您为什么更新 (Using why-did-you-update)

why-did-you-update is a library that hooks into React and detects potentially unnecessary component renders. It detects when a component’s render method is called despite its props not having changed.

why-did-you-update是一个连接到React并检测潜在不必要的组件渲染的库。 它会检测组件的属性未更改时何时调用组件的render方法。

建立 (Setup)
  1. Install with npm: npm i --save-dev why-did-you-update

    使用npm安装: npm i --save-dev why-did-you-update

  2. Add this snippet anywhere in your app:

    将此代码段添加到您的应用中的任何位置:
import React from 'react'
if (process.env.NODE_ENV !== 'production') {  const {whyDidYouUpdate} = require('why-did-you-update')  whyDidYouUpdate(React)}

Note that this tool is great in local development but make sure it’s disabled in production since it will slow down your app.

请注意 ,此工具在本地开发中非常有用,但请确保在生产中将其禁用,因为它会降低您的应用程序运行速度。

了解输出 (Understanding the output)

why-did-you-update monitors your app as it runs and logs components that may have changed unnecessarily. It lets you see the props before and after a render cycle it determined may have been unnecessary.

why-did-you-update您的应用在运行时会进行监控,并记录可能已不必要更改的组件。 它使您可以查看确定不需要的渲染周期前后的道具。

演示2 (Demo 2)

To demonstrate why-did-you-update, I installed the library in the TodoMVC app on Code Sandbox, an online React playground. Open the browser console and add some TODOs to see the output.

为了演示why-did-you-update ,我将库安装在在线React操场Code Sandbox上的TodoMVC应用程序中。 打开浏览器控制台,并添加一些TODO来查看输出。

Here’s the demo.

这是演示

Notice that a few components in the app are rendering unnecessarily. Try implementing the techniques described above to prevent unnecessary renders. If done correctly, there should be no output from why-did-you-update in the console.

注意,应用程序中的一些组件不必要地呈现。 尝试实施上述技术,以防止不必要的渲染。 如果正确完成,则控制台中的“ why-did-you-update应该没有输出。

工具3:React开发人员工具 (Tool 3: React Developer Tools)

The React Developer Tools Chrome extension has a built-in feature for visualizing component updates. This is helpful for detecting unnecessary render cycles. To use it, first make sure to install the extension here.

React Developer Tools Chrome扩展程序具有内置功能,用于可视化组件更新。 这有助于检测不必要的渲染周期。 要使用它,请首先确保在此处安装扩展程序

Then, open the extension by clicking the “React” tab in the Chrome DevTools and check “Highlight Updates”.

然后,通过单击Chrome DevTools中的“React”标签打开扩展程序,然后选中“突出显示更新”。

Then, simply use your app. Interact with various components and watch the DevTools work its magic.

然后,只需使用您的应用即可。 与各种组件进行交互,并观看DevTools发挥其魔力。

了解输出 (Understanding the output)

The React Developer Tools highlights components that are re-rendering at a given point in time. Depending on the frequency of updates, a different color is used. Blue shows infrequent updates, ranging to green, yellow, and red for components that update frequently.

React Developer Tools突出显示了在给定时间点重新渲染的组件。 根据更新频率,使用不同的颜色。 蓝色显示不频繁更新,对于频繁更新的组件,范围从绿色,黄色和红色开始。

Seeing yellow or red isn’t necessarily a bad thing. It would be expected when adjusting a slider, or other UI element that triggers frequent updates. But if you click a simple button and see red- it may mean that something is awry. The purpose of the tool is to spot components that are updating unnecessarily. As the app developer, you should have a general idea which components should be updating at a given time.

看到黄色或红色不一定是一件坏事。 调整滑块或触发频繁更新的其他UI元素时,可以预期。 但是,如果您单击一个简单的按钮并看到红色,则可能表示有问题。 该工具的目的是发现不必要更新的组件。 作为应用程序开发人员,您应该大致了解应该在给定时间更新哪些组件。

演示3 (Demo 3)

To demonstrate the component highlighting, I rigged the TodoMVC app to update some components unnecessarily.

为了演示组件突出显示,我装配了TodoMVC应用程序以不必要地更新某些组件。

Here’s the demo.

这是演示

Open the link above, and then open the React Developer Tools and enable update highlighting. When you type in the top text input, you’ll see all of the TODOs highlight unnecessarily. As you type faster, you’ll see the color change to indicate more frequent updates.

打开上面的链接,然后打开React Developer Tools并启用更新突出显示。 当您输入顶部文本输入时,您会不必要地看到所有TODO突出显示。 随着输入速度的加快,您会看到颜色变化,表明更新频率更高。

修复不必要的渲染 (Fixing unnecessary renders)

Once you’ve identified components in your app that are re-rendering unnecessarily, there are a few easy fixes.

一旦确定了应用中不必要的组件,便可以进行一些简单的修复。

使用PureComponent (Use PureComponent)

In the above example, DumbComponent is a pure function of its props. That is, the component only needs to re-render when its props change. React has a special type of component built-in called PureComponent that is meant for exactly this use case.

在上面的示例中, DumbComponent是其props的纯函数。 也就是说,仅在其道具更改时才需要重新渲染组件。 React具有一种称为PureComponent内置特殊类型的组件,正是针对此用例。

Instead of inheriting from React.Component, use React.PureComponent like this:

代替从React.Component继承,使用React.PureComponent像这样:

class DumbComponent extends PureComponent {  render() {    return <div> {this.props.value} </div>;  }}

Then, the component will only re-render when its props actually change. That’s it!

然后,仅当其道具实际更改时,组件才会重新渲染。 而已!

Note that PureComponent does a shallow comparison of props, so if you use complex data structures, it may miss some prop changes and not update your components.

请注意, PureComponentPureComponent了较浅的比较,因此,如果您使用复杂的数据结构,则可能会丢失一些属性更改而不会更新组件。

实现shouldComponentUpdate (Implement shouldComponentUpdate)

shouldComponentUpdate is a component method called before render when either props or state has changed. If shouldComponentUpdate returns true, render will be called, if it returns false, nothing happens.

propsstate发生变化时, shouldComponentUpdate是在render之前调用的组件方法。 如果shouldComponentUpdate返回true,则将调用render ;如果返回false,则什么也不会发生。

By implementing this method, you can instruct React to avoid re-rendering a given component if its props don’t change.

通过实现此方法,您可以指示React避免在其道具不变的情况下重新渲染给定的组件。

For example, we could implement shouldComponentUpdate in our dumb component from above like this:

例如,我们可以像这样从上面的哑组件中实现shouldComponentUpdate

class DumbComponent extends Component {  shouldComponentUpdate(nextProps) {    if (this.props.value !== nextProps.value) {      return true;    } else {      return false;    }  }
render() {    return <div>foo</div>;  }}

调试生产中的性能问题 (Debugging Performance Issues in Production)

The React Developer Tools only work if you are running your app on your own machine. If you’re interested in understanding performance issues that users see in production, try LogRocket.

只有在自己的机器上运行应用程序时,React Developer Tools才起作用。 如果您想了解用户在生产中看到的性能问题,请尝试LogRocket

LogRocket is like a DVR for web apps, recording literally everything that happens on your site. Instead of guessing why problems happen, you can replay sessions with bugs or performance issues to quickly understand the root cause.

LogRocket就像Web应用程序的DVR, 实际上记录了您网站上发生的所有事情。 无需猜测为什么会发生问题,您可以重播带有错误或性能问题的会话以快速了解根本原因。

LogRocket instruments your app to record performance data, Redux actions/state, logs, errors, network requests/responses with headers + bodies, and browser metadata. It also records the HTML and CSS on the page, recreating pixel-perfect videos of even the most complex single-page apps.

LogRocket对您的应用程序进行了记录,以记录性能数据,Redux动作/状态,日志,错误,带有标题和正文的网络请求/响应以及浏览器元数据。 它还将HTML和CSS记录在页面上,甚至可以对最复杂的单页面应用程序重新创建像素完美的视频。

LogRocket | Logging and Session Replay for JavaScript AppsLogRocket helps you understand problems affecting your users, so that you can get back to building great software.logrocket.com

LogRocket | JavaScript应用程序的日志记录和会话重播 LogRocket可帮助您了解影响用户的问题,以便您可以重新构建出色的软件。 logrocket.com

Thanks for reading. I hope these tools and techniques help in your next React project!

谢谢阅读。 希望这些工具和技术对您的下一个React项目有所帮助!

翻译自: https://www.freecodecamp.org/news/make-react-fast-again-tools-and-techniques-for-speeding-up-your-react-app-7ad39d3c1b82/

react性能监控根据工具

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值