Next.js 的增量静态再生 (Incremental Static Regeneration,ISR) 是一种强大的功能,它允许你在构建之后更新静态页面,而无需完全重建整个站点。 这结合了静态站点生成 (SSG) 的性能优势和服务器端渲染 (SSR) 的灵活性。
ISR 的工作原理:
- 初始构建: 在构建时,Next.js 会像静态站点生成一样预渲染页面,并生成 HTML 文件。
- 重新验证: 在运行时,当请求到达页面时,Next.js 会检查页面是否已过期。过期时间由
revalidate
属性控制(以秒为单位)。
- 后台重新生成: 如果页面已过期,Next.js 会在后台重新生成该页面。在此期间,Next.js 仍然会提供旧的缓存页面给用户。
- 更新缓存: 一旦页面重新生成完成,Next.js 会更新缓存,并在后续请求中提供新的页面。
如何使用 ISR:
在 getStaticProps
函数中添加 revalidate
属性即可启用 ISR:
import Head from "next/head"; import Layout from "../../app/layout"; import { useRouter } from "next/router";
function Post({ post, id }: any) { return ( <Layout> <div> <Head> <title>{`${id}标题`}</title> <meta name="description" content={`Post${id}页面描述`} /> <meta name="keywords" content={`文章${id}的关键词`} /> <meta name="viewport" content="initial-scale=1.0, width=device-width" /> {/* 其他SEO相关的标签 */} </Head> <h1>{JSON.stringify(post?.data)}</h1> </div> </Layout> ); }
export async function getStaticProps({ params }: any) { try { const res = await fetch( `http://43.163.243.129:1337/api/tests/${params.id}` ); if (!res.ok) { return { notFound: true, }; } const post = await res.json();
return { props: { post, id: params.id, }, revalidate: 60, }; } catch (error) { console.error("Error fetching data:", error); return { notFound: true, }; } }
export async function getStaticPaths() { const res = await fetch(`http://43.163.243.129:1337/api/tests/`); const postAll = await res.json(); const paths = postAll.data.map((post: any) => ({ params: { id: post.id.toString(), }, }));
return { paths: paths, fallback: true, }; }
export default Post;
|
刷新模版
import { NextApiRequest, NextApiResponse } from "next"
export default async function handler(req: NextApiRequest, res: NextApiResponse) { const { secret, path } = req.body; console.log(req.body);
if (secret != process.env.REVALIDATION_SECRET) { return res.status(401).json({ message: 'Invalid secret', code: 401 }); }
try { await res.revalidate(path || '/'); return res.json({ revalidated: true, message: 'success', code: 200 }); } catch (err) { return res.status(500).send('Error revalidating'); } }
|