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

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