首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在下一个js中路由更改时停止api调用。只在页面加载时调用api一次

问在下一个js中路由更改时停止api调用。只在页面加载时调用api一次
EN

Stack Overflow用户
提问于 2022-08-01 11:09:52
回答 3查看 764关注 0票数 0

我在下一个js里有一页。我只想在第一次加载页面时才调用"getServerSideprops“中的api。示例:您访问了xyz页面,我想在第一次访问时调用api。在此之后,如果您切换到任何其他页面,然后返回到这个xyz页面。如果我已经有了这个页面的数据,我想签入我的redux。我不想再调用api了。

这是代码图像

EN

回答 3

Stack Overflow用户

发布于 2022-08-01 11:18:35

服务器端呈现非常适合于获取每次呈现上更改的数据。在我看来,你的数据并没有那么频繁地改变。最好的解决办法是使用增量静态再生。生成静态页面,并以每分钟重新验证为例。

阅读更多信息,请访问:https://nextjs.org/docs/basic-features/data-fetching/incremental-static-regeneration

代码语言:javascript
复制
// 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

代码语言:javascript
复制
// 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
    }
  }
}
票数 0
EN

Stack Overflow用户

发布于 2022-08-01 11:19:43

由于您使用的是redux,所以您必须使用一个名为下一个redux包装器的库。完成目标的方式是,一旦获取数据,就可以将数据存储在redux的服务器实例中,从那里开始,您可以在发出此请求之前每次检查数据,如果存储中已经存在该特定数据。您可以在ReadMe和这个答案中了解更多有关这方面的信息。

票数 0
EN

Stack Overflow用户

发布于 2022-08-01 13:18:59

您可以设置shallow: true,它将在初始调用之后跳过getServerSideProp()调用。浅路由

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73192751

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档