如何配置Next.js参数化路由子页面并获取路由参数?
Next.js 嵌套动态路由配置问题
现有路由与需求
- 已配置路由:
https://app.com/users→pages/users/index.jshttps://app.com/users/:userid→pages/users/[id].js
- 需要新增的路由:
https://app.com/users/:id/friends:展示指定用户的全部好友https://app.com/users/:id/friends/:friendId:展示指定用户的某个特定好友
尝试的目录结构(无效)
pages users index.js [id].js friends index.js [friendId].js
当前结构只能访问users/friends,无法匹配users/:id/friends这类嵌套动态路由。
正确的目录结构设置
要实现嵌套动态路由,需要把friends目录放到[id]的子目录下,调整后结构如下:
pages users index.js [id] index.js // 原pages/users/[id].js的代码移到这里 friends index.js // 对应路由/users/:id/friends [friendId].js // 对应路由/users/:id/friends/:friendId
这样的层级完全对应路由的嵌套关系,:id作为父动态路由,friends作为它的子路由,自然能继承上层的动态参数。
在getServerSideProps中获取参数
- 在
pages/users/[id]/friends/index.js中获取用户ID:
export async function getServerSideProps(context) { const { id } = context.params; // 这里用id拉取该用户的好友数据 return { props: { id } }; }
- 在
pages/users/[id]/friends/[friendId].js中获取双参数:
export async function getServerSideProps(context) { const { id, friendId } = context.params; // 这里用id和friendId拉取对应好友的详情数据 return { props: { id, friendId } }; }
内容的提问来源于stack exchange,提问作者Pastilhas
相关产品推荐
相关产品推荐

