Next.js Page Router中fetch() API是否支持App Router同款cache选项?
Page Router 是否支持 Next.js App Router 扩展的 fetch 缓存语义?
是否支持该特性?
Page Router 不支持 App Router中那种对原生fetch() API扩展的、每个请求独立设置持久缓存语义的特性。这个自定义缓存配置是App Router专属设计,Page Router的服务端数据获取逻辑(如getServerSideProps、getStaticProps)有固定缓存规则,无法像App Router那样直接给单个fetch请求指定缓存策略。
可行实现方案
如果需要在Page Router中实现类似的请求级缓存控制,可以参考以下几种方案:
静态缓存(适用于非实时数据)
使用getStaticProps配合增量静态再生(ISR),在构建时获取数据并缓存,同时通过revalidate参数控制更新频率,适合不频繁变动的内容:export async function getStaticProps() { const res = await fetch('https://api.example.com/data'); const data = await res.json(); return { props: { data }, revalidate: 60 // 每60秒自动重新生成页面并更新缓存 }; }服务端自定义缓存(适用于实时或半实时数据)
在getServerSideProps中手动集成缓存工具(如Redis、内存缓存),自行控制每个请求的缓存过期时间、失效策略:import Redis from 'ioredis'; const redisClient = new Redis(); export async function getServerSideProps() { const cacheKey = 'api:example-data'; let cachedData = await redisClient.get(cacheKey); if (!cachedData) { // 无缓存时发起请求 const res = await fetch('https://api.example.com/data'); cachedData = JSON.stringify(await res.json()); // 设置5分钟缓存过期 await redisClient.set(cacheKey, cachedData, 'EX', 300); } return { props: { data: JSON.parse(cachedData) } }; }客户端缓存库(灵活控制客户端请求缓存)
使用SWR、React Query这类客户端数据缓存库,在组件层面控制数据获取的缓存、重新验证逻辑,弥补Page Router服务端fetch缓存的局限性:import useSWR from 'swr'; // 自定义请求函数 const fetcher = async (url) => { const res = await fetch(url); if (!res.ok) throw new Error('请求失败'); return res.json(); }; function DataComponent() { const { data, error } = useSWR('https://api.example.com/data', fetcher, { refreshInterval: 30000, // 每30秒自动刷新 revalidateOnMount: true, cacheTime: 60000 // 缓存保留1分钟 }); if (error) return <div>数据加载失败</div>; if (!data) return <div>加载中...</div>; return <div>{JSON.stringify(data)}</div>; }
内容的提问来源于stack exchange,提问作者Bảo Anh Bùi Nguyễn
相关产品推荐
相关产品推荐

