reactjs - 如何使用详尽的 deps lint 规则来安装/卸载效果

标签 reactjs react-hooks eslint

我无法理解如何使用 react-hooks/exhaustive-deps lint 规则执行与 componentDidMountcomponentWillUnmount 等效的操作是在我的应用程序中。例如,在加载组件时,我想加载一些数据并在完成后清理它。所以我可能会按照这些思路写一些东西。

React.useEffect(() => {
  loadDataById(id, other, properties);
  return () => {
    resetDataById(id);
  };
}, []);

现在的问题是我们已经包含了react-hooks lint 规则。这表明我需要在此示例的依赖项列表中包含 idotherproperties。但如果我这样做,当 otherproperties 更改时,将调用 loadDataByIdresetDataById 方法,但是我想要在组件加载/卸载时使用这些。我只能在这些特定行上禁用 lint 规则,但这似乎是我们应用程序中相当常见的东西的反模式。

最佳答案

如果您认为您的钩子(Hook)应该只运行一次且仅运行一次,即使依赖项发生变化。您始终可以使用注释指令忽略该 eslint 规则,如下所示:

React.useEffect(() => {
  loadDataById(id, other, properties);
  return () => {
    resetDataById(id);
  };
  // eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

关于reactjs - 如何使用详尽的 deps lint 规则来安装/卸载效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64582312/

相关文章:

javascript - 如何检查 redux hook 中 dispatch 的返回值

javascript - 我无法在React上正确调用其他组件中的模态组件

node.js - 通过 SASS 支持使用 Typescript、SASS 和 CSS 模块搜索 React 组件库的 Webpack 配置

reactjs - React hooks 中的 const 变量如何变化?

javascript - 使用 React Hooks,当我将 prop 从父组件传递给子组件时,子组件中的 prop 是未定义的

javascript - EsLint 与 2017 相比不起作用

eslint - 汇总和 eslint : How can I fix this error "TypeError: eslint is not a function" using eslint with rollup?

将 .eslintrc 重新定位到父级后,ESLint 找不到配置 "prettier/@typescript-eslint"

javascript - 如何测试 React 组件使用 jest 渲染列表

reactjs - Flutter中 `componentDidMount()`的等效项是什么