繁体   English   中英

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

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

我有一个关于 eslint-plugin-react-hooks 的问题。

我想减少执行 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;
}

现在自定义钩子效果很好,但 eslint-plugin-react-hooks 没那么多。 我的代码中的警告不是大问题。 我知道我可以通过添加评论来消除这个警告:

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

问题是自定义钩子参数之一是依赖项列表,而 eslint-plugin-react-hooks 不会检测到缺少的依赖项。 如何使 eslint-plugin-react-hooks 正确检测自定义钩子的依赖项列表问题? 甚至有可能对自定义钩子进行这样的检测吗?

看起来 eslint-plugin-react-hooks 不支持依赖列表作为自定义钩子中的参数(据我所知)。 正如dangerismycat 所建议的,useCallback 有一个解决方法。

所以,而不是做:

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

无需具有依赖项列表参数的自定义钩子即可实现相同的功能:

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

虽然很遗憾它引入了更多样板并且代码更难阅读,但我并不介意。

react-hooks/exhaustive-deps规则允许您检查自定义钩子。 高级配置选项:

可以配置exhaustive-deps 以使用 additionalHooks 选项验证自定义Hooks 的依赖关系。 此选项接受正则表达式以匹配具有依赖项的自定义 Hook 的名称。

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

在您的.eslintrc文件中,在“规则”配置中添加以下条目:

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

然后你应该能够调用你的钩子并看到 linter 警告并使用 Quick Fix 选项。

在此处输入图片说明

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM