Next.js组件中usePathname返回null问题求助
解决usePathname在Pages Router组件中返回null的问题
核心原因
你混淆了Next.js两种路由体系的API:
usePathname是**App Router(app目录)**专属的客户端路由钩子- 你的项目基于Pages Router(pages目录),应该使用
next/router包中的useRouter来获取路径信息
具体修复步骤
- 替换导入语句
将CustomNavbar中的usePathname导入换成useRouter:
// 旧代码 import { usePathname } from 'next/navigation' // 新代码 import { useRouter } from 'next/router'
- 修改路径获取逻辑
通过useRouter实例的pathname属性获取当前路径:
'use client' import { useRouter } from 'next/router' export default function CustomNavbar() { const router = useRouter() const currentPath = router.pathname return ( <nav> {/* 使用currentPath做导航高亮等逻辑 */} <a href="/" className={currentPath === '/' ? 'active' : ''}>首页</a> <a href="/about" className={currentPath === '/about' ? 'active' : ''}>关于</a> </nav> ) }
为什么pages/index.tsx中usePathname能正常工作?
Next.js 13.4+对Pages Router和App Router的API做了有限兼容,页面组件(pages目录下的文件)中使用App Router的钩子可能临时生效,但这属于非推荐用法,长期来看会导致兼容性问题,建议统一使用Pages Router的useRouter。
额外检查项
- 确保CustomNavbar被渲染在
_app.tsx的<Component />内部或页面组件的客户端渲染区域,不要放在路由上下文之外 - 如果你确实需要混合使用两种路由体系,确保项目配置了正确的路由兼容模式,但不推荐这种复杂场景
内容的提问来源于stack exchange,提问作者がとらいふ
相关产品推荐
相关产品推荐

