如何保存数据在状态或缓存在getServerSideProps?



我正在构建一个Next.js应用程序,它应该是SSR。所以我有一些常见的数据,例如导航和其他一些东西,我需要被服务器渲染,我需要它在每一页。但是当我在页面之间移动时,从getServerSideProps的REST API在每个页面上加载它似乎不正确。

所以我寻找一个方法来保存这个信息在一些本地缓存或状态,我不加载它第二次当我搬到另一个页面在浏览器。

有办法吗?

您可以在getServerSideProps中设置Cache-Control头以缓存其响应。

缓存与服务器端呈现文档中的示例:

// This value is considered fresh for ten seconds (s-maxage=10).
// If a request is repeated within the next 10 seconds, the previously cached value will still be fresh. 
// If the request is repeated before 59 seconds, the cached value will be  
// stale but still render (stale-while-revalidate=59). 
// In the background, a revalidation request will be made to populate the 
// cache with a fresh value. If you refresh the page, you will see the new value. 
export async function getServerSideProps({ req, res }) {
res.setHeader(
'Cache-Control', 
'public, s-maxage=10, stale-while-revalidate=59'
)
return { 
props: {} 
} 
} 

您可以根据需要配置Cache-Control头值。注意,设置Cache-Control值只在生产模式下有效,因为在开发模式下头将被覆盖。

最新更新