我在下一个js里有一页。我只想在第一次加载页面时才调用"getServerSideprops“中的api。示例:您访问了xyz页面,我想在第一次访问时调用api。在此之后,如果您切换到任何其他页面,然后返回到这个xyz页面。如果我已经有了这个页面的数据,我想签入我的redux。我不想再调用api了。
发布于 2022-08-01 11:18:35
服务器端呈现非常适合于获取每次呈现上更改的数据。在我看来,你的数据并没有那么频繁地改变。最好的解决办法是使用增量静态再生。生成静态页面,并以每分钟重新验证为例。
阅读更多信息,请访问:https://nextjs.org/docs/basic-features/data-fetching/incremental-static-regeneration
// This function gets called at build time on server-side.
// It may be called again, on a serverless function, if
// revalidation is enabled and a new request comes in
export async function getStaticProps() {
const response = await apiCall('route', 'get', null)
return {
props: {
data: response.data ?? null
},
// Next.js will attempt to re-generate the page:
// - When a request comes in
// - At most once every 10 seconds
revalidate: 10, // In seconds
}
}您还可能希望设置缓存头。下面的例子。阅读更多信息,请访问:https://nextjs.org/docs/going-to-production#caching
// 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 }) {
const response = await apiCall('route', 'get', null)
res.setHeader(
'Cache-Control',
'public, s-maxage=10, stale-while-revalidate=59'
)
return {
props: {
data: response.data ?? null
}
}
}发布于 2022-08-01 11:19:43
由于您使用的是redux,所以您必须使用一个名为下一个redux包装器的库。完成目标的方式是,一旦获取数据,就可以将数据存储在redux的服务器实例中,从那里开始,您可以在发出此请求之前每次检查数据,如果存储中已经存在该特定数据。您可以在ReadMe和这个答案中了解更多有关这方面的信息。
发布于 2022-08-01 13:18:59
您可以设置shallow: true,它将在初始调用之后跳过getServerSideProp()调用。浅路由
https://stackoverflow.com/questions/73192751
复制相似问题