You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

API嵌套动态路由失效:获取商品详情时categoryId参数未定义报错

问题解决:getStaticPaths 缺少 categoryId 参数

错误原因

你的页面路径为 /products/[categoryId]/[productId],属于嵌套动态路由,getStaticPaths 必须生成包含 categoryId 和 productId 两个参数的完整路径,而当前代码仅传入了 productId,导致Next.js无法匹配完整路由规则,抛出参数缺失错误。

修改方案

1. 修正 getStaticPaths 逻辑

需要在生成路径时同时传入 categoryId 和 productId,假设你的商品数据中包含 categoryId 字段(若没有则需从API获取商品对应的分类信息):

export async function getStaticPaths() {
  const _ApiService = new ApiServices();
  const response = await _ApiService.getAllProducts();
  const data = await response;
  
  const paths = data.data.map((item) => {
    return {
      params: {
        categoryId: item.categoryId.toString(),
        productId: item.id.toString(),
      },
    };
  });
  
  return {
    paths,
    fallback: false,
  };
}

2. 验证 getStaticProps 逻辑

如果API需要结合分类ID查询商品详情,可调整 getStaticProps 同时获取两个参数(若无需分类ID则保持原逻辑即可):

export async function getStaticProps(context) {
  const { params } = context;
  const { categoryId, productId } = params;
  
  const _ApiService = new ApiServices();
  // 根据API需求决定是否传入categoryId
  const response = await _ApiService.getProduct(productId);
  const data = await response;
  
  return {
    props: {
      data: data.data,
    },
  };
}

额外注意

  • 确保商品数据中存在有效的 categoryId,若API返回的商品信息未包含该字段,需调整API接口返回商品所属分类ID,或先获取所有分类并关联商品与分类的对应关系。
  • 嵌套动态路由的 getStaticPaths 必须生成完整的参数组合,否则Next.js无法完成页面预渲染。

内容的提问来源于stack exchange,提问作者Santhosh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 12:17:48