react-hooks/exhaustive-deps: Handle optional chained methods as dependency (#20204) (#20247)

This commit is contained in:
Ari Perkkiö 2021-03-24 18:45:27 +02:00 committed by GitHub
parent 7b84dbd169
commit eb58c3909a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 35 additions and 0 deletions

View File

@ -3629,6 +3629,36 @@ const tests = {
}, },
], ],
}, },
{
code: normalizeIndent`
function MyComponent(props) {
useEffect(() => {}, [props?.attribute.method()]);
}
`,
errors: [
{
message:
'React Hook useEffect has a complex expression in the dependency array. ' +
'Extract it to a separate variable so it can be statically checked.',
suggestions: undefined,
},
],
},
{
code: normalizeIndent`
function MyComponent(props) {
useEffect(() => {}, [props.method()]);
}
`,
errors: [
{
message:
'React Hook useEffect has a complex expression in the dependency array. ' +
'Extract it to a separate variable so it can be statically checked.',
suggestions: undefined,
},
],
},
{ {
code: normalizeIndent` code: normalizeIndent`
function MyComponent() { function MyComponent() {

View File

@ -1656,6 +1656,11 @@ function analyzePropertyChain(node, optionalChains) {
return result; return result;
} else if (node.type === 'ChainExpression' && !node.computed) { } else if (node.type === 'ChainExpression' && !node.computed) {
const expression = node.expression; const expression = node.expression;
if (expression.type === 'CallExpression') {
throw new Error(`Unsupported node type: ${expression.type}`);
}
const object = analyzePropertyChain(expression.object, optionalChains); const object = analyzePropertyChain(expression.object, optionalChains);
const property = analyzePropertyChain(expression.property, null); const property = analyzePropertyChain(expression.property, null);
const result = `${object}.${property}`; const result = `${object}.${property}`;