gpt4 book ai didi

reactjs - React Hook 依赖项 - 通用 Fetch Hook

转载 作者:行者123 更新时间:2023-12-03 15:47:24 25 4
gpt4 key购买 nike

我已经学习了很多关于如何设置我自己的自定义通用 useFetch 的教程。钩。
我想出的东西效果很好,但它违反了一些 Hooks 规则。
大多数情况下,它不使用“正确”的依赖项集。
通用 Hook 接受 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 };
}
我发现如果我从依赖项中省略选项(这是有道理的,因为我们不希望这个深层对象以我们应该监控的方式发生变化)并传播传入的依赖项,它会按预期工作。
当然,这两个变化都打破了“Hooks of Hooks”。
// 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]);
那么,我怎么可能重写它以遵循 Hooks 规则而不陷入无限刷新循环?
这是 useRequest 的完整代码使用定义的接口(interface):
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;
}

最佳答案

那是因为您在每次渲染时都重新创建了一个新数组。事实上,整个依赖没有任何意义,因为你从来没有在效果中使用它。
您同样可以依赖具有不断变化的 header 的选项对象。但是由于该对象也会在每次渲染时重新创建,因此您必须首先记住它:

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(),而不是依赖刷新索引来触发刷新。钩子(Hook)返回一个刷新函数,它在内部也会在效果中调用该函数(而不是将加载逻辑放在效果本身中,它只是调用该函数)。这样,您可以更好地遵守规则,因为 useMemo实际上从不依赖于刷新索引,因此它不应该在依赖项中。

关于reactjs - React Hook 依赖项 - 通用 Fetch Hook,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64393441/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com