我的 useQuery 钩子每次被调用时都会重新获取。我以为应该交回缓存?

My useQuery hook is refetching everytime its called. I thought it is suppose to hand back the cache?

我在这里有点困惑。我认为 react-query 在使用 useQuery 时会返回 'cache' n 个对相同“useQuery”的后续调用。但是每次我调用它时,它都会重新获取并进行网络调用。

这是执行此操作的“正确方法”吗?我认为它会自动将“缓存”版本交给我。我尝试延长 staleTime 和 cacheTime,但均无效。一直打网络电话。我还尝试了带有缓存的 initialData .. 没有用。

所以,我正在执行以下操作,但看起来很脏。

这是我的钩子:

export default function useProducts ({
 queryKey="someDefaultKey", id
}){
  const queryClient = useQueryClient();

  return useQuery(
    [queryKey, id],
    async () => {
      const cachedData = await queryClient.getQueryData([queryKey, id]);

      if (cachedData) return cachedData;

      return await products.getOne({ id })
    }, {
        enabled: !!id
       }
  );
}

这是这样发起的:

  const { refetch, data } = useProducts(
      {
        id
      }
    }
  );

我在两个 diff 位置用 onclick 调用“refetch”。我假设在我检索数据后......然后后续点击将交回缓存?

恐怕这里有很多误解:

  • react 查询在 stale-while-revalidate 上运行,因此它将为您提供缓存中的数据,然后在后台重新获取。您可以通过设置 staleTime 来自定义此行为,这将告诉图书馆数据可以被视为新鲜的时间。不会发生后台更新。
  • 当您调用 refetch 时,它将重新获取。这是势在必行的行动。如果你不想要它,请不要调用 refetch。
  • 您不需要在 queryFn 中手动从缓存中读取 - 库会为您完成。