💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
[TOC] # Understanding React Pure Components Many people get confused by the difference between a Functional Component and a Pure Component. Most of them think they are the same, but this is not true. When we use a Pure Component, we need to import PureComponent from React: 许多人对功能组件和纯组件之间的区别感到困惑。他们中的大多数人认为他们是一样的,但事实并非如此。当我们使用Pure Component时,我们需要从React导入PureComponent: ```js import React, { PureComponent } from 'react'; ``` If your React component's render method is "pure" (that means it renders the same result, given the same props and state), you can use this function to improve the performance of your application. A Pure Component performs a shallow comparison for the props and nextProps objects as well as the state and nextState objects. Pure components do not include the `shouldComponentUpdate(nextProps, nextState)` method, and if we try to add it, we will get a warning from React. 如果您的React组件的render方法是“纯粹的”(这意味着它呈现相同的结果,通过给定相同的props和state),您可以使用此函数来提高应用程序的性能。 Pure Component对 `props` 和 `nextProps` 对象以及 `state` 和 `nextState` 对象执行浅比较(*会比较 `Object.keys(state | props)` 的长度是否一致,每一个 key 是否两者都有,并且是否是一个引用,也就是只比较了第一层的值,确实很浅,所以深层的嵌套数据是对比不出来的。*)。纯组件不包括 `shouldComponentUpdate(nextProps, nextState)` 方法,如果我们尝试添加它,我们将从React收到警告。 ![](images/c008e1d9bed2ce5b5db40572a88bd2ac591140d2.png) In this recipe, we will create a basic example to understand how Pure Components works. 将创建一个基本示例来了解 Pure Components 的工作原理。 # 总结 # 与 shouldComponentUpdate 共存 如果 PureComponent 里有 `shouldComponentUpdate` 函数的话,直接使用 shouldComponentUpdate 的结果作为是否更新的依据,没有 `shouldComponentUpdate` 函数的话,才会去判断是不是 `PureComponent` ,是的话再去做 `shallowEqual` 浅比较。 ``` // 这个变量用来控制组件是否需要更新 var shouldUpdate = true; // inst 是组件实例 if (inst.shouldComponentUpdate) { shouldUpdate = inst.shouldComponentUpdate(nextProps, nextState, nextContext); } else { if (this._compositeType === CompositeType.PureClass) { shouldUpdate = !shallowEqual(prevProps, nextProps) || !shallowEqual(inst.state, nextState); } } ``` 可以用 `shouldComponentUpdate` 模拟 `PureComponent`,下面两个组件的功能一样 ```js class Demol extends Component { shouldComponentUpdate (next Props, nextState) { const { props, state) = this; function shallowCompare (a, b) { return a === b I I Object.keys(a).every(k => a[k] === b[k] ); } return shallowCompare(nextProps, props ) && shallowCompare(nextState, state); } } ``` ```js class Demo2 extends PureComponent () ``` # [PureComponent的作用及一些使用陷阱](https://www.jianshu.com/p/33cda0dc316a) 总结:如果环境支持ES6,那么应该使用`Component`;如果环境不支持ES6,那么应该使用 `createClass`;如果组件没有自身状态,那么应该使用 `FunctionalComponent` :如果组件是纯组件,那么应该使用 `PureComponent`。