简体   繁体   English

我可以为自定义挂钩使用 react-hooks/exhaustive-deps 吗?

[英]Can I have react-hooks/exhaustive-deps for a custom hook?

I wrote this hook (there could be bugs, I haven't used it yet):我写了这个钩子(可能有错误,我还没有使用它):

import { useCallback, useEffect } from 'react';
import _throttle from 'lodash/throttle';

export function useThrottledCallback(cb, delay, ...deps) {
  const callback = useCallback(_throttle(cb, delay), deps);

  useEffect(() => {
    const lastCallback = callback;

    return () => lastCallback.cancel();
  }, [callback]);

  return callback;
}

Is there a way I can make the exhaustive-deps rule lint usages of this hook?有没有办法让这个钩子的 exhaustive-deps rule lint 用法?

useThrottledCallback(() => (a + b + c)}, 100, [])

In this usage, I'd like to be notified that a , b , and c need to be in the dependency array.在此用法中,我希望收到通知abc需要位于依赖项数组中。

It should be pretty easy.这应该很容易。 The documentation says : 文件说

exhaustive-deps can be configured to validate dependencies of custom Hooks with the additionalHooks option. exhaustive-deps可以配置为使用 additionalHooks 选项验证自定义 Hooks 的依赖性。 This option accepts a regex to match the names of custom Hooks that have dependencies.此选项接受一个正则表达式来匹配具有依赖性的自定义挂钩的名称。

So you'd want something like:所以你想要这样的东西:

{
  "rules": {
    // ...
    "react-hooks/exhaustive-deps": ["warn", {
      "additionalHooks": "useThrottledCallback"
    }]
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 带有自定义 IntersectionObserver 钩子的 react-hooks/exhaustive-deps 警告 - react-hooks/exhaustive-deps warning with custom IntersectionObserver hook 反应 useEffect 带有警告的钩子 react-hooks/exhaustive-deps - React useEffect hook with warning react-hooks/exhaustive-deps 是否可以通过 useCallback 避免自定义 React Hook 上的“eslint(react-hooks/exhaustive-deps)”错误? - Is it possible to avoid 'eslint(react-hooks/exhaustive-deps)' error on custom React Hook with useCallback? 如何解决`react-hooks/exhaustive-deps`的`React Hook useEffect缺少依赖`? - How to solve `React Hook useEffect has a missing dependency` of `react-hooks/exhaustive-deps`? 由 axios 取消令牌引起的 react useEffect hook 无限循环 [react-hooks/exhaustive-deps] - react useEffect hook infinite loop caused by axios cancel token [react-hooks/exhaustive-deps] useEffect 和 'react-hooks/exhaustive-deps' linting - useEffect and 'react-hooks/exhaustive-deps' linting 在 Gatsby 中启用 react-hooks/exhaustive-deps - Enable react-hooks/exhaustive-deps in Gatsby 了解 react-hooks/exhaustive-deps useEffect 和调度事件 - understanding react-hooks/exhaustive-deps useEffect and dispatching events useCallBack react-hooks/exhaustive-deps 警告 - useCallBack react-hooks/exhaustive-deps warning react-hooks/exhaustive-deps 警告还是无限循环? - react-hooks/exhaustive-deps warning or infinite loop?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM