我在使用 useSWR 钩子时遇到了问题,要么是因为在 onMount 的多个位置被触发而获取太多次,要么是因为它不是第一次在 onMount 上运行而失败。
我的想法是简单地检查 fetcher 内的缓存,看看刷新间隔内是否已经有一个值,然后将它发回似乎有效,但我不能 100% 确定它是否会像我一样工作在外部调用 mutate 之后打算......是否有什么我忽略的原因,为什么我不应该使用这种方法?
如果在刷新间隔内调用,基本上 mutate(url) 将变得与 mutate(url, false) 相同,我认为这很好,但理想情况下我希望它正常工作。
const getTimestampKey = (key: string) => key + "--ts";
const hasExpired = (key: string) => {
const timestampKey = getTimestampKey(key);
if (!cache.has(timestampKey)) return true;
let prevTime = cache.get(timestampKey);
return Date.now() > prevTime + RefreshInterval;
};
const saveTimestamp = (key: string) => {
const timestampKey = getTimestampKey(key);
cache.set(timestampKey, Date.now());
};
export const getApplicationsByAssociationKey = (selectedAssociationId: string) => {
return `${applicationsUrl}?associationId=${selectedAssociationId}`;
};
export const getUserApplicationsFetcher = (url: string) => {
if (!url) throw new Error("Bad argument exception.");
if (!hasExpired(url)) {
let cachedData = cache.get(url);
if (cachedData) return cachedData;
}
return bffClient
.get<ApplicationsResponseArray>(url, { withCredentials: true })
.then((res) => {
saveTimestamp(url); // save the timestamp
return res.data;
});
};
export const useGetUserApplicationsByAssociationId = (selectedAssociationId: string) => {
const { data, error, mutate, isValidating } = useSWR<ApplicationsResponseArray, any>(
selectedAssociationId ? getApplicationsByAssociationKey(selectedAssociationId) : null,
getUserApplicationsFetcher,
{
refreshInterval: RefreshInterval
}
);
return {
data: (data || []) as Application[],
error: error,
loading: !data && !error,
mutate: mutate
};
};
我尝试过的选项都是:
refreshInterval:刷新间隔, revalidateOnMount:假, revalidateOnFocus:假, revalidateOnReconnect:假, refreshWhenOffline:假, refreshWhenHidden:假
或允许 revalidateOnMount 但再次尝试 onError 但两种解决方案似乎都没有按计划工作,即在刷新间隔内使用缓存数据。