UNPKG

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