簡體   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