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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. function errorMessage(node) {
  9. return `${node} does not need shouldComponentUpdate when extending React.PureComponent.`;
  10. }
  11. // ------------------------------------------------------------------------------
  12. // Rule Definition
  13. // ------------------------------------------------------------------------------
  14. module.exports = {
  15. meta: {
  16. docs: {
  17. description: 'Flag shouldComponentUpdate when extending PureComponent',
  18. category: 'Possible Errors',
  19. recommended: false,
  20. url: docsUrl('no-redundant-should-component-update')
  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. } else if (node.parent && node.parent.id) {
  46. return node.parent.id.name;
  47. }
  48. return '';
  49. }
  50. /**
  51. * Checks for violation of rule
  52. * @param {ASTNode} node The AST node being checked.
  53. */
  54. function checkForViolation(node) {
  55. if (utils.isPureComponent(node)) {
  56. const hasScu = hasShouldComponentUpdate(node);
  57. if (hasScu) {
  58. const className = getNodeName(node);
  59. context.report({
  60. node: node,
  61. message: errorMessage(className)
  62. });
  63. }
  64. }
  65. }
  66. return {
  67. ClassDeclaration: checkForViolation,
  68. ClassExpression: checkForViolation
  69. };
  70. })
  71. };