简体   繁体   English

带有依赖列表和 eslint-plugin-react-hooks 的自定义钩子

[英]Custom hooks with dependency lists and eslint-plugin-react-hooks

I have a question regarding eslint-plugin-react-hooks.我有一个关于 eslint-plugin-react-hooks 的问题。

I wanted to reduce the boilerplate code of doing a API call and storing the result into state so I created a custom hook:我想减少执行 API 调用并将结果存储到状态的样板代码,所以我创建了一个自定义钩子:

export const loading = Symbol('Api Loading');
export const responseError = Symbol('Api Error');

export function useApi<T>(
    apiCall: () => CancelablePromise<T>,
    deps: DependencyList
): T | (typeof loading) | (typeof responseError) {
    const [response, setResponse] = useState<T | (typeof loading) | (typeof responseError)>(loading);
    useEffect(() => {
        const cancelablePromise = apiCall();
        cancelablePromise.promise
            .then(r => setResponse(r))
            .catch(e => {
                console.error(e);
                setResponse(responseError);
            });
        return () => cancelablePromise.cancel();
    }, deps); // React Hook useEffect has a missing dependency: 'apiCall'. Either include it or remove the dependency array. If 'apiCall' changes too often, find the parent component that defines it and wrap that definition in useCallback (react-hooks/exhaustive-deps)
    return response;
}

Now the custom hook works great but the eslint-plugin-react-hooks not so much.现在自定义钩子效果很好,但 eslint-plugin-react-hooks 没那么多。 The warning in my code is not a big problem.我的代码中的警告不是大问题。 I know i can silence this warning by adding a comment:我知道我可以通过添加评论来消除这个警告:

// eslint-disable-next-line react-hooks/exhaustive-deps

The problem is that one of the custom hook arguments is a dependency list and eslint-plugin-react-hooks dose not detect missing dependencies on it.问题是自定义钩子参数之一是依赖项列表,而 eslint-plugin-react-hooks 不会检测到缺少的依赖项。 How do I make eslint-plugin-react-hooks correctly detect dependency list problems for my custom hook?如何使 eslint-plugin-react-hooks 正确检测自定义钩子的依赖项列表问题? Is it even possible to have such detection for custom hooks?甚至有可能对自定义钩子进行这样的检测吗?

Looks like the dependency lists as arguments in custom hooks are not supported in eslint-plugin-react-hooks (as far as i know).看起来 eslint-plugin-react-hooks 不支持依赖列表作为自定义钩子中的参数(据我所知)。 There is a workaround with useCallback as dangerismycat suggested.正如dangerismycat 所建议的,useCallback 有一个解决方法。

So instead of doing:所以,而不是做:

const apiResult = useApi(() => apiCall(a, b, c), [a, b, c]);

The same functionality can be achieved without the custom hook having a dependency list argument:无需具有依赖项列表参数的自定义钩子即可实现相同的功能:

const callback = useCallback(() => apiCall(a, b, c), [a, b, c]);
const apiResult = useApi(callback);

While its a shame that it introduces a bit more boilerplate and the code is a bit harder to read, I don't mind it too much.虽然很遗憾它引入了更多样板并且代码更难阅读,但我并不介意。

The react-hooks/exhaustive-deps rule allows you to check your custom hooks. react-hooks/exhaustive-deps规则允许您检查自定义钩子。 From the Advanced Configuration options:高级配置选项:

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.此选项接受正则表达式以匹配具有依赖项的自定义 Hook 的名称。

 { "rules": { // ... "react-hooks/exhaustive-deps": ["warn", { "additionalHooks": "(useMyCustomHook|useMyOtherCustomHook)" }] } }

In your .eslintrc file, add the following entry in the "rules" config:在您的.eslintrc文件中,在“规则”配置中添加以下条目:

'react-hooks/exhaustive-deps': ['warn', {
      'additionalHooks': '(useApi)'
    }],

Then you should be able to call your hook and see the linter warning and use the Quick Fix option.然后你应该能够调用你的钩子并看到 linter 警告并使用 Quick Fix 选项。

在此处输入图片说明

暂无
暂无

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

相关问题 React,ESLint:eslint-plugin-react-hooks 依赖于 object 中的 function - React, ESLint: eslint-plugin-react-hooks dependency on a function in an object Eslint React Hooks错误:eslint-plugin-react-hooks用尽详尽的警告警告useEffect中的功能依赖项 - Eslint React Hooks Error: eslint-plugin-react-hooks exhaustive deps warning for a function dependency in useEffect React,ESLint:eslint-plugin-react-hooks 显示不正确的“缺少依赖项” - React, ESLint: eslint-plugin-react-hooks shows incorrect “missing dependency” 为什么 eslint-plugin-react-hooks 在有条件地使用 React 钩子时不会发出警告? - Why eslint-plugin-react-hooks doesn't warn when using react hooks conditionally? eslint-plugin-react-hooks 出现意外错误(react-hooks/exhaustive-deps) - eslint-plugin-react-hooks is giving unexpected errors (react-hooks/exhaustive-deps) 与useEffect一起使用时如何防止触发useCallback(并遵守eslint-plugin-react-hooks)? - How to prevent useCallback from triggering when using with useEffect (and comply with eslint-plugin-react-hooks)? 如何让 `eslint-plugin-react-hooks` 对导出为 `default` 的功能组件进行 lint? - How can I get `eslint-plugin-react-hooks` to lint functional components that are exported as `default`? eslint-plugin-react-hooks 是否在启动时显示代码本身或终端上的错误? - Does eslint-plugin-react-hooks displays the errors on the code itself or just the terminal when starting? 在打字稿中启用react-hooks eslint插件。 tslint中没有插件 - enabling the react-hooks eslint plugin in typescript. no plugins in tslint React钩子使用eslint-plugin-react-hooks @ next附加不需要的值 - React hooks appends unwanted value with eslint-plugin-react-hooks@next
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM