next.js 如何在使用SSR和动态元数据时不进行两次查询

ggazkfy8  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(105)

我使用Next.js 13与应用程序路由系统,正如你在代码中看到的。我设置了FetchingProudct,这是SSR。它调用一个API,用于生成动态元数据的MetaData和一个用于发送数据属性以使用客户端页面组件的API。我担心fetchingProduct可能会运行两次。我使用了react cache,但我不确定它是否有效。有没有更好的方法或什么可以解决的?

import { use,cache } from 'react'
import ProductDetail from '../components/ProductDetail';

const FetchingProduct = cache(async({id})=> {
    const response = await fetch(
        `http://127.0.0.1:8000/api/product/${id}`,
        {cache : 'no-store'}
    );
    return response.json()
  });

const FetchingRecommnandProduct = cache(async({id})=> {
    const response = await fetch(
        `http://127.0.0.1:8000/api/product/recommandation/${id}`,
        {cache : 'no-store'}
    );
    return response.json()
  });

export async function generateMetadata({ params, searchParams }, parent) {
  // read route params
  const id = params.id
  
  // fetch data
  const product = await FetchingProduct({id})

  // optionally access and extend (rather than replace) parent metadata
  const previousImages = (await parent).openGraph?.images || []
  
  return {
    title: product?.name,
    description: product?.description,
    openGraph: {
      images: [`http://127.0.0.1:8000${product?.images[0]?.image}`, ...previousImages],
    },
  }
}

  export default function Product({ params }) {
    const {id} = params
    const productData = use(FetchingProduct({id}))
    const recommandProductData = use(FetchingRecommnandProduct({id}))
    return (
      <div>
        <ProductDetail 
        product={productData}
        recommandProduct={recommandProductData}
        />
      </div>
    );
  }```

I wrapped my SSR function with react cache, but I am not sure that it fetches once and can be used for multiple places. Any better approaches for that?
qnyhuwrf

qnyhuwrf1#

如果你在服务器上使用fetch()获取相同的API,Nextjs将缓存具有相同输入的获取请求并重用它们。你不用担心。Source here..

相关问题