Next.js:如何在请求时构建页面并保存?
解决按需生成并缓存页面的问题
方案1:改用Incremental Static Regeneration(ISR)替代getServerSideProps
你不需要依赖getServerSideProps实现“请求时构建”,Next.js的ISR功能完全能满足需求,还能自动缓存生成的页面,避免构建时生成上万页面的问题:
- 在页面组件中使用
getStaticProps,并添加revalidate参数(单位:秒) - 构建时只生成少量指定页面(通过
getStaticPaths的fallback: 'blocking'配置),其他页面在第一次被请求时才生成并缓存 - 缓存的页面会在
revalidate设定的时间后自动重新生成,保证内容新鲜度
示例代码:
export async function getStaticProps({ params }) { const data = await fetch(`https://api.example.com/posts/${params.id}`); const post = await data.json(); return { props: { post }, // 每60秒重新验证并更新缓存 revalidate: 60, }; } export async function getStaticPaths() { return { // 构建时仅生成这些路径的页面 paths: [{ params: { id: '1' } }], // 未预生成的路径,请求时自动构建并缓存 fallback: 'blocking', }; }
方案2:给getServerSideProps添加自定义缓存层
如果坚持要用getServerSideProps,可以手动实现页面缓存逻辑:
- 选择缓存存储方式:比如Redis、文件系统或内存缓存(注意内存缓存会随服务器重启失效)
- 在
getServerSideProps逻辑最开始,根据请求路径检查缓存是否存在 - 缓存存在则直接返回缓存内容;不存在则执行数据获取和渲染逻辑,再将结果存入缓存
示例代码(文件系统缓存示例):
import fs from 'fs'; import path from 'path'; export async function getServerSideProps(context) { const cacheDir = path.join(process.cwd(), '.cache'); const cachePath = path.join(cacheDir, `${context.params.id}.json`); // 检查缓存是否存在 if (fs.existsSync(cachePath)) { const cachedData = JSON.parse(fs.readFileSync(cachePath, 'utf8')); return { props: cachedData }; } // 正常数据获取逻辑 const data = await fetch(`https://api.example.com/posts/${context.params.id}`); const post = await data.json(); // 将结果写入缓存 if (!fs.existsSync(cacheDir)) fs.mkdirSync(cacheDir); fs.writeFileSync(cachePath, JSON.stringify(post)); return { props: { post } }; }
注意:自定义缓存需要自行处理过期、清理等逻辑,相比ISR更繁琐,优先推荐方案1。
内容的提问来源于stack exchange,提问作者imback0526
相关产品推荐
相关产品推荐

