[英]NEXT.js ISR remove static page
我對 ISR 有一點問題。 我有 revalidate 道具等於 1 像這里
export async function getStaticProps({ params }) {
const data = await client.getEntries({
content_type: "product",
"fields.name": params.slug,
});
if (!data.items[0]) {
return {
notFound: true,
};
}
return {
props: {
article: data.items[0],
revalidate: 1,
},
};
}
當我在 Contentful 中創建產品時,頁面按預期創建。 當我想進入不存在的頁面時,我得到了預期的 404 錯誤。 當我在現有產品的 Contentful 中更改某些內容或刪除它時,問題就開始了。
當我在 Contentful 中刪除產品時,產品頁面中的產品列表會更新並且產品會消失,但我仍然可以進入該產品的頁面。 此外,當我重命名產品名稱時,產品列表會更新,但我仍然可以進入較早的頁面名稱。
有什么辦法可以解決這個問題嗎?
獲取靜態路徑
export async function getStaticPaths() {
const data = await client.getEntries({
content_type: "product",
});
return {
paths: data.items.map((item) => ({
params: { slug: item.fields.name },
})),
fallback: true,
};
}
產品頁面
const Article = ({ article }) => {
const router = useRouter();
if (router.isFallback) return <p>Loading...</p>;
return (
<div>
<h1>Hello! {article.fields.name}</h1>
<Link href="/about">
<a>Back to about!</a>
</Link>
</div>
);
};
編輯當我在我的 product77 版本中重新驗證 static 頁面后,在 Contentful 中將產品名稱從“product77”更改為“product7”時仍然存在,我仍然可以進入該頁面。
重新驗證后不應該刪除嗎?
如果相應地配置了getStaticPaths
和getStaticProps
,則無法刪除已刪除的頁面,但會使用 404 而不是使用On-demand Revalidation提供已刪除的頁面。
// /pages/blog/[...post].jsx
function Post({ postData }) {
return (
// ...
);
}
export async function getStaticPaths() {
const res = await fetch("https://.../posts");
const posts = await res.json();
// Prerender paths during build
const paths = posts.map((post) => ({
params: { post: post.id },
}));
return { paths, fallback: "blocking" };
}
export async function getStaticProps(context) {
const res = await fetch(`https://.../posts/${context.params.post}`);
const postData = await res.json();
if(!postData){
// The page doesn't exist in the CMS, return notFound to trigger a 404
return{
notFound: true,
revalidate: 30
}
}
// Return page props
return {
props: {
postData,
},
revalidate: 30,
};
}
上述代碼的主要內容是:
getStaticPaths
中預渲染路徑getStaticPaths
必須使用"blocking"
或true
作為fallback
值getStaticProps
中的未知路徑(感謝后備)。 如果 CMS 中不存在該頁面,則返回notFound: true
觸發 404 頁面然后,在 webhook 中使用按需重新驗證方法:
// /pages/api/revalidate-post.js
export async function handler(req, res) {
try {
const reqBody = JSON.parse(req.body);
await res.revalidate(`/${reqBody.path}`);
return res.json({ revalidated: true });
} catch (err) {
return res.status(500).send("Error revalidating");
}
}
res.revalidate(
/${reqBody.path} )
使用來自getStaticProps
的邏輯調用對頁面的全新評估。
現在,如果有人要刪除 CMS 中的頁面,並為已刪除的頁面路徑觸發上述重新驗證 webhook 處理程序,那么該路徑將提供 404 頁面而不是原始頁面。
然而,頁面本身並沒有從磁盤中刪除。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.