[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收到警告。

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`。