Skip to content

Commit 9d4a59f

Browse files
committed
Fix props handling when destructured in constructor (fixes #639)
1 parent 46c8008 commit 9d4a59f

File tree

2 files changed

+30
-4
lines changed

2 files changed

+30
-4
lines changed

lib/rules/prop-types.js

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -545,11 +545,14 @@ module.exports = Components.detect(function(context, components, utils) {
545545
node.id.properties[i].value.type === 'ObjectPattern'
546546
);
547547
// let {firstname} = props
548-
var statelessDestructuring = node.init.name === 'props' && utils.getParentStatelessComponent();
548+
var directDestructuring =
549+
node.init.name === 'props' &&
550+
(utils.getParentStatelessComponent() || inConstructor())
551+
;
549552

550553
if (thisDestructuring) {
551554
properties = node.id.properties[i].value.properties;
552-
} else if (statelessDestructuring) {
555+
} else if (directDestructuring) {
553556
properties = node.id.properties;
554557
} else {
555558
continue;
@@ -784,9 +787,13 @@ module.exports = Components.detect(function(context, components, utils) {
784787
// let {props: {firstname}} = this
785788
var thisDestructuring = destructuring && node.init.type === 'ThisExpression';
786789
// let {firstname} = props
787-
var statelessDestructuring = destructuring && node.init.name === 'props' && utils.getParentStatelessComponent();
790+
var directDestructuring =
791+
destructuring &&
792+
node.init.name === 'props' &&
793+
(utils.getParentStatelessComponent() || inConstructor())
794+
;
788795

789-
if (!thisDestructuring && !statelessDestructuring) {
796+
if (!thisDestructuring && !directDestructuring) {
790797
return;
791798
}
792799
markPropTypesAsUsed(node);

tests/lib/rules/prop-types.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2120,6 +2120,25 @@ ruleTester.run('prop-types', rule, {
21202120
errors: [{
21212121
message: '\'lastname\' is missing in props validation'
21222122
}]
2123+
}, {
2124+
code: [
2125+
'class Hello extends React.Component {',
2126+
' constructor(props, context) {',
2127+
' super(props, context)',
2128+
' const firstname = props.firstname;',
2129+
' const {lastname} = props;',
2130+
' this.state = {',
2131+
' firstname,',
2132+
' lastname',
2133+
' }',
2134+
' }',
2135+
'}'
2136+
].join('\n'),
2137+
parser: 'babel-eslint',
2138+
errors: [
2139+
{message: '\'firstname\' is missing in props validation'},
2140+
{message: '\'lastname\' is missing in props validation'}
2141+
]
21232142
}
21242143
]
21252144
});

0 commit comments

Comments
 (0)