no-redundant-should-component-update.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /**
  2. * @fileoverview Flag shouldComponentUpdate when extending PureComponent
  3. */
  4. 'use strict';
  5. const astUtil = require('../util/ast');
  6. const componentUtil = require('../util/componentUtil');
  7. const docsUrl = require('../util/docsUrl');
  8. const report = require('../util/report');
  9. // ------------------------------------------------------------------------------
  10. // Rule Definition
  11. // ------------------------------------------------------------------------------
  12. const messages = {
  13. noShouldCompUpdate: '{{component}} does not need shouldComponentUpdate when extending React.PureComponent.',
  14. };
  15. module.exports = {
  16. meta: {
  17. docs: {
  18. description: 'Disallow usage of shouldComponentUpdate when extending React.PureComponent',
  19. category: 'Possible Errors',
  20. recommended: false,
  21. url: docsUrl('no-redundant-should-component-update'),
  22. },
  23. messages,
  24. schema: [],
  25. },
  26. create(context) {
  27. /**
  28. * Checks for shouldComponentUpdate property
  29. * @param {ASTNode} node The AST node being checked.
  30. * @returns {Boolean} Whether or not the property exists.
  31. */
  32. function hasShouldComponentUpdate(node) {
  33. const properties = astUtil.getComponentProperties(node);
  34. return properties.some((property) => {
  35. const name = astUtil.getPropertyName(property);
  36. return name === 'shouldComponentUpdate';
  37. });
  38. }
  39. /**
  40. * Get name of node if available
  41. * @param {ASTNode} node The AST node being checked.
  42. * @return {String} The name of the node
  43. */
  44. function getNodeName(node) {
  45. if (node.id) {
  46. return node.id.name;
  47. }
  48. if (node.parent && node.parent.id) {
  49. return node.parent.id.name;
  50. }
  51. return '';
  52. }
  53. /**
  54. * Checks for violation of rule
  55. * @param {ASTNode} node The AST node being checked.
  56. */
  57. function checkForViolation(node) {
  58. if (componentUtil.isPureComponent(node, context)) {
  59. const hasScu = hasShouldComponentUpdate(node);
  60. if (hasScu) {
  61. const className = getNodeName(node);
  62. report(context, messages.noShouldCompUpdate, 'noShouldCompUpdate', {
  63. node,
  64. data: {
  65. component: className,
  66. },
  67. });
  68. }
  69. }
  70. }
  71. return {
  72. ClassDeclaration: checkForViolation,
  73. ClassExpression: checkForViolation,
  74. };
  75. },
  76. };