Next.js 14报错:Unsupported Server Component type: undefined 求助
在学习Next.js 14官方仪表盘教程的「显示激活链接」章节时,给侧边栏的NavLinks组件添加'use client';指令、usePathname和clsx后,出现了"Unsupported Server Component type: undefined"错误,组件代码如下:
"use client"; import { UserGroupIcon, HomeIcon, DocumentDuplicateIcon, } from "@heroicons/react/24/outline"; import clsx from "clsx"; import Link from "next/link"; import { usePathname } from "next/navigation"; // 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; 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": pathname === link.href, } )} > <LinkIcon className="w-6" /> <p className="hidden md:block">{link.name}</p> </Link> ); })} </> ); }
这个错误通常是客户端组件中试图渲染未正确解析的组件(此处为图标组件)或Next.js组件兼容性问题导致的,以下是针对性解决步骤:
检查Heroicons安装与导入正确性
- 确保已安装依赖:
npm install @heroicons/react - 核对图标组件的名称和导入路径,@heroicons/react v2的outline图标路径
@heroicons/react/24/outline是正确的,需确认UserGroupIcon、HomeIcon等名称与官方图标库一致。
- 确保已安装依赖:
将links数组移至组件内部
把导航链接数组从组件外部移到NavLinks函数内部,避免静态外部引用引发的组件解析异常:"use client"; import { UserGroupIcon, HomeIcon, DocumentDuplicateIcon, } from "@heroicons/react/24/outline"; import clsx from "clsx"; import Link from "next/link"; import { usePathname } from "next/navigation"; export default function NavLinks() { const pathname = usePathname(); // 将links数组移至组件内部 const links = [ { name: "Home", href: "/dashboard", icon: HomeIcon }, { name: "Invoices", href: "/dashboard/invoices", icon: DocumentDuplicateIcon, }, { name: "Customers", href: "/dashboard/customers", icon: UserGroupIcon }, ]; return ( <> {links.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": pathname === link.href, } )} > <LinkIcon className="w-6" /> <p className="hidden md:block">{link.name}</p> </Link> ); })} </> ); }重启开发服务器
Next.js开发缓存可能引发异常,停止当前服务器后重新运行npm run dev,清除缓存后再测试。核对Next.js版本
确保使用Next.js 14.x版本,查看版本:npm list next版本不符则执行升级:
npm install next@latest
内容的提问来源于stack exchange,提问作者meylis Gurbanmyradow
相关产品推荐
相关产品推荐

