提问人:Choi Chan Hwan 提问时间:11/15/2023 更新时间:11/15/2023 访问量:44
在 Next.js 中,fetch 不返回新数据,而是返回现有数据 [duplicate]
In Next.js, fetch does not return new data, it returns existing data [duplicate]
问:
我正在尝试在Next.js中使用fetch作为SSG方法。
但是,我在模拟服务器中注册的“content”值与实际显示的值不同。
下面是我的代码。
import Layout_Mobile from "@/components/Layout/DeviceLayout/Layout_Mobile";
import Layout_PC from "@/components/Layout/DeviceLayout/Layout_PC";
import PostDetailPage from "@/components/PostDetailPage/PostDetailPage";
const fetchPosts = async (params) => {
const res = await fetch(
`https://5875183d-18c0-49ad-b99d-8deeb4ded6a9.mock.pstmn.io/posts/${params.slug}`
)
.then((response) => response.json())
.then((data) => {
return data;
});
return res;
};
export const generateStaticParams = async () => {
const res = await fetch(
"https://5875183d-18c0-49ad-b99d-8deeb4ded6a9.mock.pstmn.io/posts"
)
.then((response) => response.json())
.then((data) => {
return data;
});
return res.map((post) => ({
slug: post.id.toString(),
}));
};
const page = async ({ params }) => {
const { title, summary, content, author, createdAt } = await fetchPosts(
params
);
return (
<div>
<Layout_Mobile></Layout_Mobile>
<Layout_PC>
<PostDetailPage
title={title}
description={summary}
content={content}
author={author}
date={createdAt}
/>
</Layout_PC>
</div>
);
};
export default page;
我预期的结果(我在 postman 中输入的值。即新值)
{
"content": "test1 "
}
实际结果(之前注册的值)
{
...previous json data
}
如何解决这个问题?
感谢您的阅读。
我尝试了 SSG,但它失败了......我想解决这个问题。
答:
0赞
Fabio Nettis
11/15/2023
#1
您面临的问题与Next.js缓存单个获取请求的方式有关。当您在构建时静态生成页面,并且除了第一个选项之外不提供以下任何选项时,在第一次提取后将只返回缓存的结果。
您可以将不同的选项传递给每个请求以定义其行为:
强制缓存
此请求应被缓存,直到手动失效,类似于在页面路由器内仅调用一次(在构建时)的方式。这是默认值,如果省略,则应用。getStaticProps
const response = await fetch("https://api.example.com", {
cache: "force-cache",
});
没有商店
应在每个请求上重新获取此请求。与在 Pages 路由器内调用每个请求的方式类似。getServerSideProps
const response = await fetch("https://api.example.com", {
cache: "no-store",
});
重新验证
此请求应缓存 10 秒的生存期,然后才会失效。类似于页面路由器中的选项。getStaticProps
revalidate
const response = await fetch("https://api.example.com", {
next: { revalidate: 10 },
});
您可以在官方文档中找到有关这些不同行为的更多信息。
评论