为什么`unstable_cache`不在nextjs中缓存数据?

问题描述 投票:0回答:1

我正在尝试在服务器组件上使用

unstable_cache
来缓存数据以提高性能。然而,它似乎不起作用。

下面是我的代码。每次请求到来时,都会从 React 组件渲染函数中调用

fetchProductWithCache
。重新生效时间为 10 秒。我假设 10 秒内的所有请求都不应该从
fetchProductWithDelay
方法调用
fetchProductWithCache
。但是,我可以看到每个请求都有 1 秒的延迟,并且日志
fetch product from unstable_cache
会打印在每个请求上。所以看起来
unstable_cache
并没有真正缓存任何东西。

我做错了什么?


export const runtime = 'edge'; // I want to deploy to all edge locations
export const revalidate = 10;

const fetchProductWithCache = async (country?: Country) => {
  const product = await unstable_cache(
    async () => {
      console.log('fetch product from unstable_cache');
      return fetchProductWithDelay(country);
    },
    ['product'],
    { revalidate: 10, tags: ['product'] }
  )();
  return product;
};

export const generateStaticParams = async () => {
  const countries = await api.product.countries();
  console.log('[PRODUCT] generating static paths:', countries);
  return countries.map((country) => ({ country }));
};

export default async function Page({ params }: { params: Props }) {
  const { country } = params;
  console.log('[PRODUCT] generating static product:', country);
  const product: any =  await fetchProductWithCache(country)
  const parityPrice = getDiscountedPrice(product.price, product.discount);

  if (Object.keys(country).length === 0 || country === null || !product) {
    return <div />;
  }
  return (
    <>
      <div className="ml-14 lg:ml-24 -mb-40 lg:-mb-56">
   ...
reactjs next.js
1个回答
0
投票

unstable_cach 应该用于包装整个函数(fetchProductWithCache)

export const fetchProductWithCache = unstable_cache(
    async (country: string) => {
       return fetchProductWithDelay(country)
    },
    ['product'],
    { revalidate: 10, tags: ['product'] },
);

© www.soinside.com 2019 - 2024. All rights reserved.