【问题标题】:NextJS getStaticProps is making mulitple requests to the same endpoint with fallback: true下一个 JS getStaticProps 正在向同一个端点发出多个请求,并使用 fallback: true
【发布时间】:2021-06-27 00:03:49
【问题描述】:

我注意到我的下一个应用程序在页面加载时向我的后端发出大量请求。我正在使用 getStaticPaths 和 getStaticProps 在构建时未构建路径时使用回退。 getServerSideProps 甚至在我的开发环境中都不会发生多个请求。仅在部署到 Vercel 时。我什至尝试使用 JSONplaceholder API 创建一个小型应用程序,但查看 Vercel 函数日志,它似乎仍然发出多个请求。

import { useRouter } from "next/router";

export default function Home({ todos }) {
  const router = useRouter();
  if (router.isFallback) {
    return <p>Loading....</p>;
  }
  return (
    <div>
      <pre>{JSON.stringify(todos)}</pre>
    </div>
  );
}

export async function getStaticPaths() {
  return {
    paths: [],
    fallback: true,
  };
}

export async function getStaticProps() {
  const data = await fetch(`https://jsonplaceholder.typicode.com/todos`);
  const todos = await data.json();

  return { props: { todos }, revalidate: 10 };
}

这就是 Vercel 上的回退和缓存的工作方式吗? 谢谢

【问题讨论】:

  • “我的下一个应用程序在页面加载时向我的后端发出大量请求” - 这是在 single 页面加载上吗?您是否看到 getStaticProps 中的提取请求针对单个页面请求发生多次?
  • 是的,单页请求。
  • 这在 Vercel 上是预期的,不是您的应用程序的问题。它不会导致性能下降。这是我们的代理如何处理增量生成页面的一部分。
  • 它确实会导致我的性能下降,因为它会通过多次请求相同的信息来访问我的服务器,从而导致一些惊人的结果。但如果这是它的工作方式,我猜我无能为力

标签: reactjs next.js vercel


【解决方案1】:

您可以轻松地在 getStaticProps() 内置函数中发出任何请求,因为它在构建时运行,您可以通过 props 对象传递任何请求的数据,例如下面的代码

 export const getStaticProps = async () => {
  
      const res1 = await fetch('');
      const res2 = await fetch('');

  return {
    props: { res1,res2 },
  };
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-30
    • 2019-12-11
    • 2012-06-26
    • 2019-04-18
    • 1970-01-01
    • 1970-01-01
    • 2021-09-09
    • 1970-01-01
    相关资源
    最近更新 更多