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
相关产品推荐
相关产品推荐

