【问题标题】:eslint-plugin-react-hooks is giving unexpected errors (react-hooks/exhaustive-deps)eslint-plugin-react-hooks 出现意外错误(react-hooks/exhaustive-deps)
【发布时间】:2023-03-24 19:53:01
【问题描述】:

我有一个问题,我的 vscode eslint 给了我错误的警告。我在 react 组件中有一个简单的函数,我正在尝试使用 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

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

【问题讨论】:

    标签: reactjs react-hooks create-react-app eslint


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2021-09-03
      • 2022-08-18
      • 2020-06-09
      • 2020-05-01
      • 2021-04-15
      • 2020-06-08
      • 2020-01-18
      • 2021-03-23
      • 2019-11-26
      相关资源
      最近更新 更多