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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. /** @type {import('eslint').Rule.RuleModule} */
  16. module.exports = {
  17. meta: {
  18. docs: {
  19. description: 'Disallow usage of shouldComponentUpdate when extending React.PureComponent',
  20. category: 'Possible Errors',
  21. recommended: false,
  22. url: docsUrl('no-redundant-should-component-update'),
  23. },
  24. messages,
  25. schema: [],
  26. },
  27. create(context) {
  28. /**
  29. * Checks for shouldComponentUpdate property
  30. * @param {ASTNode} node The AST node being checked.
  31. * @returns {boolean} Whether or not the property exists.
  32. */
  33. function hasShouldComponentUpdate(node) {
  34. const properties = astUtil.getComponentProperties(node);
  35. return properties.some((property) => {
  36. const name = astUtil.getPropertyName(property);
  37. return name === 'shouldComponentUpdate';
  38. });
  39. }
  40. /**
  41. * Get name of node if available
  42. * @param {ASTNode} node The AST node being checked.
  43. * @return {string} The name of the node
  44. */
  45. function getNodeName(node) {
  46. if (node.id) {
  47. return node.id.name;
  48. }
  49. if (node.parent && node.parent.id) {
  50. return node.parent.id.name;
  51. }
  52. return '';
  53. }
  54. /**
  55. * Checks for violation of rule
  56. * @param {ASTNode} node The AST node being checked.
  57. */
  58. function checkForViolation(node) {
  59. if (componentUtil.isPureComponent(node, context)) {
  60. const hasScu = hasShouldComponentUpdate(node);
  61. if (hasScu) {
  62. const className = getNodeName(node);
  63. report(context, messages.noShouldCompUpdate, 'noShouldCompUpdate', {
  64. node,
  65. data: {
  66. component: className,
  67. },
  68. });
  69. }
  70. }
  71. }
  72. return {
  73. ClassDeclaration: checkForViolation,
  74. ClassExpression: checkForViolation,
  75. };
  76. },
  77. };