NextJS 13 获取请求记忆

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

我正在使用 NextJS 13 开发 React 项目,但在使用

request memoization
代表
fetch
时遇到问题。即使在同一个请求中,它也总是向后端发送请求。

我在

http://localhost:8088/test
有一个简单的端点,它只记录一些内容以检查是否收到请求。我的
page.tsx
中有以下代码。当我重新加载页面时,我在后端服务器中看到 4 个日志; 2 来自元数据 2 来自页面。即使是完全相同的请求,也不会按照 NextJS 文档

中的说明进行重复数据删除

我在这里错过了什么,为什么

fetch('http://localhost:8088/test')
实际上被执行了四次。如何使用请求记忆,以便我可以在
Page
generateMetadata
中使用相同的数据,并且此代码仅执行一次请求?

import { Metadata } from 'next';

export const dynamic = 'force-static';
export const fetchCache = 'force-no-store';

async function getItem() {
  const res = await fetch('http://localhost:8088/test');
  return res.json();
}

export async function generateMetadata(): Promise<Metadata> {
  getItem();
  getItem();
  return {
    metadataBase: new URL('localhost:3000'),
    title: 'test'
  };
}

export default async function Page() {
  getItem();
  getItem();
  return (
    <>
      <p>test</p>
    </>
  );
}
reactjs next.js next.js13 react-typescript memoization
1个回答
0
投票

您应该在

fetch
方法中禁用缓存。请记住,在 NextJs 中,一切都基于转换,而不是配置:

const res = await fetch(
  'http://localhost:8088/test',
  { cache: 'no-store' }
);

通过使用此转换,NextJs 将了解不要在此组件中缓存任何内容。

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