-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
/
Copy pathstate-in-constructor.js
67 lines (59 loc) · 1.81 KB
/
state-in-constructor.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/**
* @fileoverview Enforce the state initialization style to be either in a constructor or with a class property
* @author Kanitkorn Sujautra
*/
'use strict';
const astUtil = require('../util/ast');
const componentUtil = require('../util/componentUtil');
const docsUrl = require('../util/docsUrl');
const report = require('../util/report');
// ------------------------------------------------------------------------------
// Rule Definition
// ------------------------------------------------------------------------------
const messages = {
stateInitConstructor: 'State initialization should be in a constructor',
stateInitClassProp: 'State initialization should be in a class property',
};
module.exports = {
meta: {
docs: {
description: 'Enforce class component state initialization style',
category: 'Best Practices',
recommended: false,
url: docsUrl('state-in-constructor'),
},
messages,
schema: [{
enum: ['always', 'never'],
}],
},
create(context) {
const option = context.options[0] || 'always';
return {
'ClassProperty, PropertyDefinition'(node) {
if (
option === 'always'
&& !node.static
&& node.key.name === 'state'
&& componentUtil.getParentES6Component(context)
) {
report(context, messages.stateInitConstructor, 'stateInitConstructor', {
node,
});
}
},
AssignmentExpression(node) {
if (
option === 'never'
&& componentUtil.isStateMemberExpression(node.left)
&& astUtil.inConstructor(context)
&& componentUtil.getParentES6Component(context)
) {
report(context, messages.stateInitClassProp, 'stateInitClassProp', {
node,
});
}
},
};
},
};