Skip to content

Commit b26d1cc

Browse files
committed
Add prevState and nextState support to no-unused-state (fixes #1759)
1 parent 3aac310 commit b26d1cc

File tree

2 files changed

+53
-2
lines changed

2 files changed

+53
-2
lines changed

lib/rules/no-unused-state.js

+10-2
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ module.exports = {
7777
// JSX attributes), then this is again set to null.
7878
let classInfo = null;
7979

80-
// Returns true if the given node is possibly a reference to `this.state`.
80+
// Returns true if the given node is possibly a reference to `this.state`, `prevState` or `nextState`.
8181
function isStateReference(node) {
8282
node = uncast(node);
8383

@@ -91,7 +91,15 @@ module.exports = {
9191
classInfo.aliases &&
9292
classInfo.aliases.has(node.name);
9393

94-
return isDirectStateReference || isAliasedStateReference;
94+
const isPrevStateReference =
95+
node.type === 'Identifier' &&
96+
node.name === 'prevState';
97+
98+
const isNextStateReference =
99+
node.type === 'Identifier' &&
100+
node.name === 'nextState';
101+
102+
return isDirectStateReference || isAliasedStateReference || isPrevStateReference || isNextStateReference;
95103
}
96104

97105
// Takes an ObjectExpression node and adds all named Property nodes to the

tests/lib/rules/no-unused-state.js

+43
Original file line numberDiff line numberDiff line change
@@ -491,6 +491,49 @@ eslintTester.run('no-unused-state', rule, {
491491
}
492492
}`,
493493
parser: 'babel-eslint'
494+
},
495+
{
496+
code: `class ESLintExample extends Component {
497+
constructor(props) {
498+
super(props);
499+
this.state = {
500+
id: 123,
501+
};
502+
}
503+
static getDerivedStateFromProps(nextProps, prevState) {
504+
if (prevState.id === nextProps.id) {
505+
return {
506+
selected: true,
507+
};
508+
}
509+
return null;
510+
}
511+
render() {
512+
return (
513+
<h1>{this.state.selected ? 'Selected' : 'Not selected'}</h1>
514+
);
515+
}
516+
}`,
517+
parser: 'babel-eslint'
518+
},
519+
{
520+
code: `class ESLintExample extends Component {
521+
constructor(props) {
522+
super(props);
523+
this.state = {
524+
id: 123,
525+
};
526+
}
527+
shouldComponentUpdate(nextProps, nextState) {
528+
return nextState.id === nextProps.id;
529+
}
530+
render() {
531+
return (
532+
<h1>{this.state.selected ? 'Selected' : 'Not selected'}</h1>
533+
);
534+
}
535+
}`,
536+
parser: 'babel-eslint'
494537
}
495538
],
496539

0 commit comments

Comments
 (0)