Home >Web Front-end >JS Tutorial >How to avoid re-rendering in React_javascript tips

How to avoid re-rendering in React_javascript tips

不言
不言Original
2018-04-10 15:12:441292browse

This article mainly introduces how to avoid re-rendering in React. Now I share it with everyone, and it can also be a reference for friends in need

Re-rendering of components

We can store any type of data in props and state in React components, and control the state of the entire component by changing props and state. When props and state change, React will re-render the entire component. The process of component re-rendering can be simplified as follows:

The translator’s previous understanding of diff is that for For a component that changes props, diff can automatically calculate the difference in the DOM tree inside the component, and then through comparison, find the DOM nodes that actually changed, and render the changed parts. This is a wrong understanding. The diff algorithm is only used to calculate the component/virtual node that changes state or props, and this component/virtual node will be re-rendered no matter how big it is.

Suppose there is a rendered component, as shown below:

Next, because of the state change, the green node in the picture below needs to be re-rendered. , as shown below:

The general idea is that you only need to update the three green nodes below to complete the component update

However! As long as the props or state of the component change, the entire component will be re-rendered. Therefore, in addition to the three green nodes mentioned above, all yellow nodes need to be re-rendered

In addition to the three nodes that are necessary for rendering, other nodes that are unnecessary for rendering are also rendered, which is a big waste of performance. For complex pages, this will result in a very poor overall page experience. Therefore, to improve the performance of components, you should do everything you can to reduce unnecessary rendering.

shouldComponentUpdate

shouldComponentUpdateThis function will be called before the component is re-rendered. The return value of the function determines whether the component needs to be re-rendered. The default return value of the function is true, which means that as long as the props or state of the component change, the virtual DOM will be rebuilt, then compared using the diff algorithm, and then based on the comparison result it will be decided whether to re-render the entire component. The return value of the function is false, which means no re-rendering is required.

The function returns true by default.

PureRenderMixin

React officially provides the PureRenderMixin plug-in. The function of the plug-in is to use it when it is not necessary. Let the function shouldComponentUpdate return false. Using this plug-in can reduce unnecessary re-rendering and obtain a certain degree of performance improvement. The usage method is as follows:

  import PureRenderMixin from 'react-addons-pure-render-mixin';
  class FooComponent extends React.Component {
   constructor(props) {
    super(props);
    this.shouldComponentUpdate = PureRenderMixin.shouldComponentUpdate.bind(this);
   }

   render() {
    return <p className={this.props.className}>foo</p>;
   }
  }

We need to rewrite shouldComponentUpdate in the component. The definition of PureRenderMixin.shouldComponentUpdate in the PureRenderMixin source code is as follows

  shouldComponentUpdate(nextProps, nextState) {
    return shallowCompare(this, nextProps, nextState);
  }

The rewritten method is based on the current component A shallow comparison is made between the state and the next state of the component. If the state of the component changes, the return result is false. If the state does not change, the return result is true

  shouldComponentUpdate(nextProps, nextState) {
    return !shallowEqual(this.props, nextProps) ||
        !shallowEqual(this.state, nextState);
  }

In the latest version of React, the base class of React.PureComponent is provided without using this plug-in.

Translator's Note: So when a larger component decides to re-render, we can bind a new shouldComponentUpdate method to each sub-component, which can reduce the number of re-renders of the sub-component. .

We can rewrite the shouldComponentUpdate function ourselves so that it can compare anything, that is, deep comparison (comparison through layer by layer recursion). Deep comparison is very time-consuming. , it is generally not recommended to do this, because it is necessary to ensure that the time spent on comparison is less than the time spent on re-rendering the entire component. At the same time, in order to reduce the time spent on comparison, we should ensure that props and state are as simple as possible and do not add unnecessary attributes. Put it in state. Attributes that can be calculated from other attributes should not be put in state.

Immutable.js

Comparison of complex data is very time-consuming and may not be possible. This problem can be solved well by using Immutable.js , The basic principle of Immutable.js is to return the same reference for unchanged objects, and to return new references for changed objects. Therefore, for status comparison, you only need to use the following code:

  shouldComponentUpdate() {
    return ref1 !== ref2;
  }

We also need to rewrite the shouldComponentUpdate method in the subcomponent.

Pure Component

如果一个组件只和 props 和 state 有关系,给定相同的 props 和 state 就会渲染出相同的结果,那么这个组件就叫做纯组件,换一句话说纯组件只依赖于组件的 props 和 state,下面的代码表示的就是一个纯组件。

   render() {
     return (
       <p style={{width: this.props.width}}>
           {this.state.rows}
       </p>
     );
  }

如果某个子组件的 props 是固定的不会发生变化,我们叫做无状态组件。在这个组件里面使用 pureRenderMixin 插件,能够保证 shouldComponentUpdate 的返回一直为 false。所以,分清纯组件和无状态组件,在无状态组件中重写shouldComponentUpdate方法是最好的选择。

key

在写动态子组件的时候,如果没有给动态子项添加key prop,则会报一个警告。这个警告指的是,如果每一个子组件是一个数组或者迭代器的话,那么必须有一个唯一的key prop,那么这个key prop是做什么的呢?
我们想象一下,假如需要渲染一个有5000项的成绩排名榜单,而且每隔几秒就会更新一次排名,其中大部分排名只是位置变了,还有少部分是完全更新了,这时候key就发挥作用了,它是用来标识当前的唯一性的props。现在尝试来描述这一场景

  [{
   sid: &#39;10001&#39;,
   name: &#39;sysuzhyupeng&#39;
  }, {
   sid: &#39;10008&#39;,
   name: &#39;zhyupeng&#39;
  }, {
   sid: &#39;120000&#39;,
   name: &#39;yupeng&#39;
  }]

其中sid是学号,那么我们来实现成绩排名的榜单

  import React from &#39;react&#39;;
  function Rank({ list }){
    return (
     <ul>
       {list.map((entry, index)=>(
         <li key={index}>{entry.name}</li>
       ))}
     </ul>
    )
  }

我们把key设成了序号,这么做的确不会报警告了,但这样是非常低效的做法,这个key是用来做virtual Dom diff的,上面的做法相当于用了一个随机键,那么不论有没有相同的项,更新都会重新渲染。

正确的做法非常简单,只需要把key的内容换成sid就可以了。

那么还有另一个问题,当key相同的时候,React会怎么渲染呢,答案是只渲染第一个相同key的项,且会报一个警告。

相关推荐:

代码详解React Js 微信分享封装

在React里使用Vuex的具体步骤

react怎样实现页面代码分割和按需加载

The above is the detailed content of How to avoid re-rendering in React_javascript tips. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn