react性能优化中,提到的就是通过 React.PureComponent 替换 React.Component 组件进行编程。
两个组件之间的不同主要就是PureComponent做了shouldComponentUpdate的优化。对props和state进行了第一层的值===比较, 并且对 context 的变化不进行判断。
通过查看React可以看到
1 /** 2 * Copyright (c) 2013-present, Facebook, Inc. 3 * All rights reserved. 4 * 5 * This source code is licensed under the BSD-style license found in the 6 * LICENSE file in the root directory of this source tree. An additional grant 7 * of patent rights can be found in the PATENTS file in the same directory. 8 * 9 * @typechecks 10 * 11 */ 12 13 /*eslint-disable no-self-compare */ 14 15 'use strict'; 16 17 var hasOwnProperty = Object.prototype.hasOwnProperty; 18 19 /** 20 * inlined Object.is polyfill to avoid requiring consumers ship their own 21 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is 22 */ 23 function is(x, y) { 24 // SameValue algorithm 25 if (x === y) { 26 // Steps 1-5, 7-10 27 // Steps 6.b-6.e: +0 != -0 28 // Added the nonzero y check to make Flow happy, but it is redundant 29 return x !== 0 || y !== 0 || 1 / x === 1 / y; 30 } else { 31 // Step 6.a: NaN == NaN 32 return x !== x && y !== y; 33 } 34 } 35 36 /** 37 * Performs equality by iterating through keys on an object and returning false 38 * when any key has values which are not strictly equal between the arguments. 39 * Returns true when the values of all keys are strictly equal. 40 */ 41 function shallowEqual(objA, objB) { 42 if (is(objA, objB)) { 43 return true; 44 } 45 46 if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) { 47 return false; 48 } 49 50 var keysA = Object.keys(objA); 51 var keysB = Object.keys(objB); 52 53 if (keysA.length !== keysB.length) { 54 return false; 55 } 56 57 // Test for A's keys different from B. 58 for (var i = 0; i < keysA.length; i++) { 59 if (!hasOwnProperty.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) { 60 return false; 61 } 62 } 63 64 return true; 65 } 66 67 module.exports = shallowEqual;