1
1
/**
2
- * @fileoverview State initialization in an ES6 class component should be in a constructor
2
+ * @fileoverview Enforce the state initialization style to be either in a constructor or with a class property
3
3
* @author Kanitkorn Sujautra
4
4
*/
5
5
'use strict' ;
@@ -19,21 +19,41 @@ module.exports = {
19
19
recommended : false ,
20
20
url : docsUrl ( 'state-in-constructor' )
21
21
} ,
22
- schema : [ ]
22
+ schema : [ {
23
+ enum : [ 'always' , 'never' ]
24
+ } ]
23
25
} ,
24
26
25
- create : Components . detect ( ( context , components , utils ) => ( {
26
- ClassProperty : function ( node ) {
27
- if (
28
- ! node . static &&
29
- node . key . name === 'state' &&
30
- utils . isES6Component ( node . parent . parent )
31
- ) {
32
- context . report ( {
33
- node,
34
- message : 'State initialization should be in a constructor'
35
- } ) ;
27
+ create : Components . detect ( ( context , components , utils ) => {
28
+ const option = context . options [ 0 ] || 'always' ;
29
+ return {
30
+ ClassProperty : function ( node ) {
31
+ if (
32
+ option === 'always' &&
33
+ ! node . static &&
34
+ node . key . name === 'state' &&
35
+ utils . isES6Component ( node . parent . parent )
36
+ ) {
37
+ context . report ( {
38
+ node,
39
+ message : 'State initialization should be in a constructor'
40
+ } ) ;
41
+ }
42
+ } ,
43
+ AssignmentExpression ( node ) {
44
+ if (
45
+ option === 'never' &&
46
+ node . left . object . type === 'ThisExpression' &&
47
+ node . left . property . name === 'state' &&
48
+ node . parent . parent . parent . parent . kind === 'constructor' &&
49
+ utils . isES6Component ( node . parent . parent . parent . parent . parent . parent )
50
+ ) {
51
+ context . report ( {
52
+ node,
53
+ message : 'State initialization should be in a class property'
54
+ } ) ;
55
+ }
36
56
}
37
- }
38
- } ) )
57
+ } ;
58
+ } )
39
59
} ;
0 commit comments