Next.js中params参数未定义问题:浏览器可见但取值失败
解决Next.js App Router中params始终为undefined的问题
你的核心问题是page组件的参数接收方式错误,在Next.js App Router的Server Component中,路由参数params是包含在单个props对象里的,不是第二个独立参数。
修正代码
把原来的参数写法调整为直接从props中解构params:
interface Props { params: { id: string }; } const CategoryPage = async (props: Props) => { // 从props中解构出params.id const { id } = props.params; let notes = await getNotes(id); // 后续页面渲染逻辑 return ( <div> {/* 页面内容 */} </div> ); }; export default CategoryPage;
额外优化建议
- 避免Server Component中调用API路由:既然你的page是Server Component,完全可以让
getNotes直接执行数据库查询逻辑,不用通过app/api/xxx/route.ts做中转,减少不必要的网络请求,提升性能。 - 确认路由结构正确性:你的页面路径
app/category/[id]/page.tsx是正确的动态路由写法,访问/category/xxx时,xxx会被捕获为params.id的值,确保访问路径符合这个格式。
内容的提问来源于stack exchange,提问作者letmeeatbrioche
相关产品推荐
相关产品推荐

