Eslint在React中使用回调钩子错误



我使用回调钩子来停止渲染由于作为props传递的函数更改而更改的组件,在每次渲染中。在这里,我为incrementSalaryincrementAge添加了回调钩子。在这种情况下,回调钩子似乎工作得很好。但是eslint抛出以下错误:

Line 10:76:  React Hook useCallback has an unnecessary dependency: 'age'. Either exclude it or remove the dependency array     react-hooks/exhaustive-deps
Line 15:5:   React Hook useCallback has an unnecessary dependency: 'salary'. Either exclude it or remove the dependency array  react-hooks/exhaustive-dep

如果我没有包含回调钩子,并且我点击了任何一个按钮。它呈现父组件中的所有其他按钮。我相信发生这种情况是因为我的函数没有被记忆,而使用回调钩子和添加依赖使我的函数被记忆。所以只有被点击的特定按钮才会被渲染。我不明白为什么eslint会向我抛出错误,是由于错误地使用回调还是由于错误地使用prevState?

import React, { useState, useCallback } from "react";
import Title from "./Title";
import Count from "./Count";
import Button from "./Button";
function ParentComponent() {
const [age, setAge] = useState(22);
const [salary, setSalary] = useState(25000);
const incrementAge = useCallback(() => setAge((prevAge) => prevAge + 1), [
age,
]);
const incrementSalary = useCallback(
() => setSalary((prevSalary) => prevSalary + 5000),
[salary]
);
return (
<div>
<Title>Use Callback Hook</Title>
<Count text="Age" count={age} />
<Button handleClick={incrementAge}>Increment Age</Button>
<Count text="Salary" count={salary} />
<Button handleClick={incrementSalary}>Increment Salary</Button>
</div>
);
}
export default ParentComponent;

这是useCallback钩子即将出现的警告/错误。您不需要在useCallback钩子中添加agesalary作为依赖项。这是因为在回调中没有对这些状态的实际依赖。

const incrementAge = useCallback(
() => setAge((prevAge) => prevAge + 1),
[]); // Remove dependency.
const incrementSalary = useCallback(
() => setSalary((prevSalary) => prevSalary + 5000),
[]); // Remove dependency.

最新更新