首页 > 解决方案 > eslint-plugin-react-hooks 出现意外错误(react-hooks/exhaustive-deps)

问题描述

我有一个问题,我的 vscode eslint 给了我错误的警告。我在反应组件中有一个简单的函数,我正在尝试使用 useCallBack 钩子进行优化。

这是一个简单的函数,我得到两个道具,并且在我创建的 params 对象中使用,根据文档,我将这两个道具作为 useCallBack 的依赖项。

const Test = ({ ReportAddressNumber, ClientNumber }) => {
const [test, setTest] = useState({ count: 0 });
const fetchSampleIDs = useCallback(() => {
  setTest(true);
  const URL = `/Samples`;
  const params = {
    ReportAddressNumber,
    ClientNumber,
  };

  fetch(URL, params)
}, [ClientNumber, ReportAddressNumber]);

useEffect(() => {
  fetchSampleIDs();
}, [fetchSampleIDs]);

 return <h1>{test.count}</h1>;
};

现在问题出在 vscode 中,它告诉我这两个道具作为 useCallback 中的依赖项是不必要的。

React Hook useCallback has unnecessary dependencies: 'ClientNumber' and 'ReportAddressNumber'. Either exclude them or remove the dependency array.eslint(react-hooks/exhaustive-deps)

在此处输入图像描述

我可以用我的.eslintrcpackage.json文件重现这个。我创建了这个代码框来解决这个问题,为了查看实际问题,您需要将代码框导出为 zip 并运行npm install并在 vscode 中查看它。

https://codesandbox.io/s/kind-mahavira-fvsub

我在这里感谢您的知识和贡献,谢谢。

标签: reactjsreact-hookscreate-react-appeslint

解决方案


花了4个小时后,我终于得到了答案。

存在冲突的依赖关系。我使用eslint-config-airbnb: 16.1.0的不包括任何 react-hooks linting 配置。但是,我自己安装了eslint-plugin-react-hookseslint-config-aribnb版本冲突的。

eslint-config-airbnb按照说明升级解决了我的问题。如果有人有同样的问题。


推荐阅读