【问题标题】:Error: A required parameter (productId) was not provided as a string in getStaticPaths for /products/[productId]错误:未在 getStaticPaths 中为 /products/[productId] 提供所需参数 (productId) 作为字符串
【发布时间】:2021-10-05 05:22:11
【问题描述】:

我想展示来自 JSON 的 3 个产品。我正在尝试做一个 NextJS Web 应用程序。我只是在学习,当我复制教程时,一切都是正确的,但我正在做自己的更改,并尝试创建不同的东西,但它不起作用。

谢谢大家!

 [
  {
    "id": "price_1JDUeIIpi9NgmDuQlNYIwAlP",
    "title": "HarryPotter1",
    "category": "Cuento",
    "image": "/images/harrypotter1.jpeg",
    "price": 20
  },
  {
    "id": "price_1JDUe4Ipi9NgmDuQh9nA4B9E",
    "title": "Harry Potter2",
    "category": "Novela",
    "image": "/images/harrypotter2.jpeg",
    "price": 10
  },
  {
    "id": "price_1JDUdqIpi9NgmDuQGOQO9HGj",
    "title": "Harry Potter3",
    "category": "Ensayo",
    "image": "/images/harrypotter3.jpeg",
    "price": 25
  }
] 
]

在不同的路线与链接。这是我的 [productId].js 文件的最后一部分:

export async function getStaticProps({ params = {} }) {
  const product = products.find(({ id }) => `${id}` === `${params.productId}`);
  return {
    props: {
      product
    },
  };
}

export async function getStaticPaths() {
  const paths = products.map((product) => {
    const { id } = product;
    return {
      params: {
        productId: id,
      },
    };
  });

  return {
    paths,
    fallback: false
  };
}

我从 Chrome 获取:错误:在 getStaticPaths 中没有为 /products/[productId] 提供所需参数 (productId) 作为字符串

【问题讨论】:

  • 你的getStaticPaths 中的products 变量来自哪里?该数组中的所有项目是否都具有有效的id?在映射它们之前,您可能希望过滤掉任何不存在的项目。

标签: javascript reactjs next.js getstaticprops getstaticpaths


【解决方案1】:

我只能根据错误描述假设:

const { id } = product;
    return {
      params: {
        productId: id,
      },
    };

getStaticPaths 函数的这一部分中,您应该为productId 提供id 作为字符串(可能是一个单独的数字)。 所以你会想尝试把它改成这样:

const { id } = product;
    return {
      params: {
        productId: id.toString(),
      },
    };

如果这就是您要找的,请告诉我。

【讨论】:

  • 嗨!谢谢。我知道我的问题不是很清楚,我只是在学习。这就是 Chrome 所说的:` 124 |返回 { 125 |参数:{ > 126 | productId: id.toString(), | ^ 127 | }, 128 | }; 129 | });`
  • @PauMarch 您好,请编辑您的问题并添加显示错误的控制台屏幕截图,而不仅仅是从整个内容中复制一行。这样我就可以帮助您找出问题所在。
猜你喜欢
  • 2021-12-12
  • 2021-09-04
  • 1970-01-01
  • 2021-08-26
  • 1970-01-01
  • 2023-02-12
  • 2019-06-21
  • 2017-02-23
  • 1970-01-01
相关资源
最近更新 更多