![](/img/trans.png)
[英]React Hooks JS Lint warning useEffect has a missing dependency
[英]Resolving TypeScript React JS Lint: React Hook useEffect has a missing dependency without using comment to disable lint or without passing dependency
我正在使用 React JS 和 TypeScript 构建一个 Web 应用程序。 我正在使用 React 钩子。 我创建了一个自定义挂钩并在组件中使用它,并在组件内的 useEffect 挂钩内调用该挂钩的 function,如下所示。
const Products: FC<{}> = () => {
const productsHook = useProducts();
useEffect(() => {
productsHook.fetchProducts();
}, []);
当我运行 lint 时,我收到以下警告。
React Hook useEffect has a missing dependency: 'productsHook'. Either include it or remove the dependency array react-hooks/exhaustive-deps
当我添加以下行时,
// eslint-disable-next-line react-hooks/exhaustive-deps
在这一行之后, productsHook.fetchProducts();
,它解决了警告。
解决问题的另一种方法是将productsHook.fetchProducts
作为数组元素添加到useEffect
的第二个参数中,就像这样。
useEffect(() => {
productsHook.fetchProducts();
}, [productsHook.fetchProducts]);
但是,从技术上讲,没有必要这样做。 如果我们不这样做,它会很好地工作。 有没有办法解决该警告而无需忽略注释或不传递useEffect
的第二个参数中的依赖关系?
我只是用第二种方法,将 function 添加到依赖数组中。 例如,在 Redux 中使用dispatch
时建议执行的操作,即使dispatch
function 保证始终相同,eslint 无法检测到,解决它的最简单方法是将其添加到依赖关系数组中。 与养成禁用您不喜欢的警告的习惯相比,这绝对是一个更好的选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.