部署Next.js到Vercel时触发usePathname Hook调用错误求助
问题解决:Vercel构建时usePathname Hook报错
错误原因
你的代码在本地运行正常,但Vercel构建过程中,ESLint的react-hooks/rules-of-hooks规则对函数嵌套调用场景产生了误判——实际usePathname是在组件顶层调用的,只是你定义的isActiveLink函数在map回调中被调用并引用了pathname,导致规则误识别为Hook在回调内调用。
修复方案
直接将激活链接的判断逻辑内联到map回调中,去掉中间的isActiveLink函数,即可避免ESLint误判:
'use client'; import { UserGroupIcon, HomeIcon, DocumentDuplicateIcon, } from '@heroicons/react/24/outline'; import Link from 'next/link'; import { usePathname } from 'next/navigation'; import clsx from 'clsx'; // Map of links to display in the side navigation. // Depending on the size of the application, this would be stored in a database. const links = [ { name: 'Home', href: '/dashboard', icon: HomeIcon }, { name: 'Invoices', href: '/dashboard/invoices', icon: DocumentDuplicateIcon, }, { name: 'Customers', href: '/dashboard/customers', icon: UserGroupIcon }, ]; export default function NavLinks() { const pathname = usePathname(); return ( <> {links.map((link) => { const LinkIcon = link.icon; // 直接在这里判断当前链接是否激活 const active = pathname === link.href; return ( <Link key={link.name} href={link.href} className={clsx( 'flex h-[48px] grow items-center justify-center gap-2 rounded-md bg-gray-50 p-3 text-sm font-medium hover:bg-sky-100 hover:text-blue-600 md:flex-none md:justify-start md:p-2 md:px-3', { 'bg-sky-100 text-blue-600': active, }, )} > <LinkIcon className="w-6" /> <p className="hidden md:block">{link.name}</p> </Link> ); })} </> ); }
其他可选方案
如果需要保留函数式判断逻辑,可以用useMemo预计算所有链接的激活状态,避免在map回调中调用函数:
'use client'; // ... 其他导入和links定义 export default function NavLinks() { const pathname = usePathname(); // 预计算所有链接的激活状态 const linksWithActive = useMemo(() => { return links.map(link => ({ ...link, active: pathname === link.href })); }, [pathname]); return ( <> {linksWithActive.map((link) => { const LinkIcon = link.icon; return ( <Link key={link.name} href={link.href} className={clsx( 'flex h-[48px] grow items-center justify-center gap-2 rounded-md bg-gray-50 p-3 text-sm font-medium hover:bg-sky-100 hover:text-blue-600 md:flex-none md:justify-start md:p-2 md:px-3', { 'bg-sky-100 text-blue-600': link.active, }, )} > <LinkIcon className="w-6" /> <p className="hidden md:block">{link.name}</p> </Link> ); })} </> ); }
内容的提问来源于stack exchange,提问作者masete
相关产品推荐
相关产品推荐

