PureComponent.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import {
  2. Component
  3. } from './Component';
  4. import {
  5. inherits
  6. } from './util';
  7. export function PureComponent(props, key, ref, context) {
  8. return Component.apply(this, arguments);
  9. }
  10. var fn = inherits(PureComponent, Component);
  11. //返回false 则不进行之后的渲染
  12. fn.shouldComponentUpdate = function (nextProps, nextState, context) {
  13. var ret = true;;
  14. var a = shallowEqual(this.props, nextProps);
  15. var b = shallowEqual(this.state, nextState);
  16. if (a === true && b === true) {
  17. ret = false;
  18. }
  19. return ret;
  20. }
  21. export function shallowCompare(instance, nextProps, nextState) {
  22. var ret = true;;
  23. var a = shallowEqual(instance.props, nextProps);
  24. var b = shallowEqual(instance.state, nextState);
  25. if (a === true && b === true) {
  26. ret = false;
  27. }
  28. return ret;
  29. }
  30. export function shallowEqual(now, next) {
  31. if (Object.is(now, next)) {
  32. return true;
  33. }
  34. //必须是对象
  35. if ((now && typeof now !== 'object') || (next && typeof next !== 'object')) {
  36. return false;
  37. }
  38. var keysA = Object.keys(now);
  39. var keysB = Object.keys(next);
  40. if (keysA.length !== keysB.length) {
  41. return false;
  42. }
  43. // Test for A's keys different from B.
  44. for (var i = 0; i < keysA.length; i++) {
  45. if (!hasOwnProperty.call(next, keysA[i]) || !Object.is(now[keysA[i]], next[keysA[i]])) {
  46. return false;
  47. }
  48. }
  49. return true;
  50. }