反应挂钩依赖关系-通用提取挂钩

时间:2020-10-16 16:58:52

标签: reactjs react-hooks

我已经按照许多教程来学习如何设置自己的自定义通用useFetch挂钩。 我想出的方法效果很好,但它违反了一些“挂钩规则”。 通常,它不使用“正确的”依赖项。

通用钩子接受URL,选项和依赖项。 将依赖关系设置为全部三个会创建无限刷新循环,即使依赖关系没有变化

// Infinite useEffect loop - happy dependencies
const UseRequest: <T>(url: string, options?: Partial<UseRequestOptions> | undefined, dependencies?: any[]) => UseRequestResponse<T>
 = <T>(url: string, options: Partial<UseRequestOptions> | undefined = undefined, dependencies: any[] = []): UseRequestResponse<T> => {
    const [data, setData] = useState<T | undefined>();
    const [loading, setLoading] = useState<boolean>(false);
    const [error, setError] = useState<UseRequestError | undefined>();

    useEffect(() => {
        let ignore = false;
        (async () => {
            try {
                setLoading(true);
                const response = await (options ? fetch(url) : fetch(url, options))
                    .then(res => res.json() as Promise<T>);
                if (!ignore) setData(response);
            } catch (err) {
                setError(err);
            } finally {
                setLoading(false);
            }
        })();
        return (() => { ignore = true; });
    }, [url, options, dependencies]);
    return { data, loading, error };
}

我发现,如果我忽略依赖项中的选项,它会按预期工作(这很有意义,因为我们不希望这个深层对象以我们应该监视的方式发生变化)并传播传入的依赖项。 当然,这两个更改都违反了“挂钩规则”。

// Working - mad dependencies
const UseRequest: <T>(url: string, options?: Partial<UseRequestOptions> | undefined, dependencies?: any[]) => UseRequestResponse<T>
 = <T>(url: string, options: Partial<UseRequestOptions> | undefined = undefined, dependencies: any[] = []): UseRequestResponse<T> => {
    const [data, setData] = useState<T | undefined>();
    const [loading, setLoading] = useState<boolean>(false);
    const [error, setError] = useState<UseRequestError | undefined>();

    useEffect(() => {
        let ignore = false;
        (async () => {
            try {
                setLoading(true);
                const response = await (options ? fetch(url) : fetch(url, options))
                    .then(res => res.json() as Promise<T>);
                if (!ignore) setData(response);
            } catch (err) {
                setError(err);
            } finally {
                setLoading(false);
            }
        })();
        return (() => { ignore = true; });
    }, [url, ...dependencies]);
    return { data, loading, error };
}

...然后我像这样使用

export const GetStuff: () => UseRequestResponse<Stuff[]> & { refresh: () => void } = () => {
    const { appToken } = GetAppToken();
    const [refreshIndex, setRefreshIndex] = useState(0);
    return {
        ...UseRequest<Stuff[]>('https://my-domain.api/v1/stuff', {
            method: 'GET',
            headers: {
                'Authorization': `Bearer ${appToken}`
            }
        }, [appToken, refreshIndex]),
        refresh: () => setRefreshIndex(refreshIndex + 1),
    };
};

注意,工作状态和损坏状态之间的唯一变化是:

}, [url, options, dependencies]);

...至:

}, [url, ...dependencies]);

那么,我怎么可能重写它以遵循钩子规则,而又不陷入无限刷新循环中?

以下是带有定义的接口的useRequest的完整代码:

import React, { useState, useEffect } from 'react';

const UseRequest: <T>(url: string, options?: Partial<UseRequestOptions> | undefined, dependencies?: any[]) => UseRequestResponse<T>
 = <T>(url: string, options: Partial<UseRequestOptions> | undefined = undefined, dependencies: any[] = []): UseRequestResponse<T> => {
    const [data, setData] = useState<T | undefined>();
    const [loading, setLoading] = useState<boolean>(false);
    const [error, setError] = useState<UseRequestError | undefined>();

    useEffect(() => {
        let ignore = false;
        (async () => {
            try {
                setLoading(true);
                const response = await (options ? fetch(url) : fetch(url, options))
                    .then(res => res.json() as Promise<T>);
                if (!ignore) setData(response);
            } catch (err) {
                setError(err);
            } finally {
                setLoading(false);
            }
        })();
        return (() => { ignore = true; });
    }, [url, ...dependencies]);
    return { data, loading, error };
}

export default UseRequest;

export interface UseRequestOptions {
    method: string;
    mode: 'cors', // no-cors, *cors, same-origin
    cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
    credentials: 'same-origin', // include, *same-origin, omit
    headers: {
        [prop: string]: string;
    },
    redirect: string, // manual, *follow, error
    referrerPolicy: string, // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
    body: string | { [prop: string]: any };
    [prop: string]: any;
};

export interface UseRequestError {
    message: string;
    error: any;
    code: string | number;
    [prop: string]: any;
}

export interface UseRequestResponse<T> {
    data: T | undefined;
    loading: boolean;
    error: Partial<UseRequestError> | undefined;
}

2 个答案:

答案 0 :(得分:5)

那是因为您在每个渲染器上重新创建了一个新数组。实际上,整个依赖没有意义,因为您永远不会在效果内部使用它。

您同样可以依赖具有变化的标题的options对象。但是由于该对象也会在每个渲染器上重新创建,因此您必须首先记住它:

export const GetStuff: () => UseRequestResponse<Stuff[]> & { refresh: () => void } = () => {
    const { appToken } = GetAppToken();
    const [refreshIndex, setRefreshIndex] = useState(0);

    const options = useMemo(() => ({
        method: 'GET',
        headers: {
            'Authorization': `Bearer ${appToken}`
        }
    }), [appToken, refreshIndex])

    return {
        ...UseRequest<Stuff[]>('https://my-domain.api/v1/stuff', options),
        refresh: () => setRefreshIndex(refreshIndex + 1),
    };
};

然后,可以使useRequest()钩子返回刷新函数,而不是依赖刷新索引来触发刷新,该钩子在内部也可以在效果中调用该函数(而不是将加载逻辑放入效果中本身,它只是调用该函数)。这样一来,您就可以更好地遵循规则,因为useMemo实际上从不依赖刷新索引,因此它不应该位于依赖关系中。

答案 1 :(得分:0)

我想我不明白您为什么要使用效果来获得此效果。我在最新项目中一直在使用外部挂钩来提取fetch方法,然后可以在需要数据时调用该方法。如果您需要对数据流的恒定引用,则可以使用react SWR,这是两者的示例。

import { useCallback } from 'react'

export function useGetUserFromCoverage() {
const getUserFromCoverage = useCallback(
        async (url) => {
            const result = await fetch(url)
            return result
},
        []
    )

    return getUserFromCoverage
}

import { useCallback } from 'react'
import useSWR from 'swr'

export function useGetHubUser(url) {
    const getHubUser = useCallback(
        async (url: string) => {
            const result = await fetch(url)
            return result
        },
        []
    )

    const { data, error } = useSWR(url, getHubUser)

    return { fetch: { data, error } }
}