securityos/node_modules/eslint-plugin-react/lib/rules/state-in-constructor.js

68 lines
1.8 KiB
JavaScript
Raw Normal View History

2024-09-06 15:32:35 +00:00
/**
* @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: 'Stylistic Issues',
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,
});
}
},
};
},
};