【问题标题】:Next js failing on build with getStaticProps due to param being undefined由于参数未定义,下一个 js 使用 getStaticProps 构建失败
【发布时间】:2022-01-04 11:36:46
【问题描述】:

开始出现导致构建失败的奇怪错误,

我们的 pages 目录中有一个 post/[id].tsx 文件,该文件使用 getStaticPropsgetStaticPaths

--道具

export const getStaticProps: GetStaticProps = async ({ params }) => {
  const res: Response = await fetch(`${baseUrl}/api/products/${params.id}`);

  const data: Product[] = await res.json();

  return {
    props: {
      data,
    },
  };
};

-- 路径

export const getStaticPaths: GetStaticPaths = async () => {
  const res: Response = await fetch(`${baseUrl}/api/products`);
  const { data } = await res.json();

  const paths = data.map((product: Product) => ({
    params: { id: product.id.toString() },
  }));
  return { paths, fallback: "blocking" };
};

在本地运行 npm run dev,一切正常,但运行 npm run build 并出现错误

Type error: Object is possibly 'undefined'.

getStaticProps 函数内部

> 12 |   const res: Response = await fetch(`${baseUrl}/api/products/${params.id}`);
                                                                      ^

现在奇怪的是,当前在 vercel 上部署的构建使用完全相同的代码来构建此页面,并且没有任何改变。但是现在构建突然失败了?

【问题讨论】:

    标签: typescript next.js


    【解决方案1】:

    这里的问题是 next.js 在这里进行类型检查并且 typescript 认为您的参数可能在这里未定义。告诉 typescript 它不是。

      const id = params.id!
      const res: Response = await fetch(`${baseUrl}/api/products/${id}`);
    

    这应该可行。

    【讨论】:

    • 嘿,这行得通,谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-04
    • 2019-11-13
    • 2021-10-20
    • 1970-01-01
    • 2021-04-02
    • 2019-10-15
    • 2019-09-08
    相关资源
    最近更新 更多