Next.js通过next/router跳转时getServerSideProps仅执行一次不刷新数据如何解决?
问题根因
Next.js的Pages Router默认对使用getServerSideProps的页面开启客户端路由缓存:当你通过<Link>做客户端跳转(无页面刷新)访问已访问过的页面时,会直接复用之前缓存的props,不会重新触发服务端的getServerSideProps执行,只有首次直接输入URL访问(走服务端首次渲染)时才会拉取最新数据。
解决方案
你可以选择以下任意一种方案禁用缓存,强制每次访问都执行getServerSideProps:
- 方案1:在
getServerSideProps返回值中添加禁用缓存的响应头
修改getGenericServerSideProps的返回逻辑,添加Cache-Control头强制不缓存页面数据:
export const getGenericServerSideProps = (slices: string[], ...callbacks) => async ( context: NextPageContext ): Promise<any> => { const appConfiguration = getAppConfiguration(); const props = await getInitialProps(slices, callbacks)(context); return { props: { ...props, appConfiguration }, // 新增缓存控制头 headers: { 'Cache-Control': 'no-store, no-cache, must-revalidate, proxy-revalidate', }, // 可选:设置revalidate为0,完全禁用增量缓存 revalidate: 0 }; };
- 方案2:禁用
<Link>组件的预加载缓存
给所有跳转该页面的<Link>添加prefetch={false}属性,关闭提前预加载和缓存逻辑:
<Link href={ROUTES[Pages.Home]} as={ROUTES[Pages.Home]} prefetch={false}> <a>Link</a> </Link>
- 方案3:如果需要全局关闭所有页面的
getServerSideProps缓存,可以在next.config.js中添加配置:
module.exports = { experimental: { // 禁用客户端路由缓存(Next.js 12+支持) clientRouterFilter: false, }, }
内容的提问来源于stack exchange,提问作者Andrei Flavius
相关产品推荐
相关产品推荐

