我在nextjs中使用新的应用程序路由器,得到错误:useRouter只在客户端组件中工作,添加“使用客户端”指令来使用它

ftf50wuq  于 2023-06-22  发布在  其他
关注(0)|答案(1)|浏览(394)
./app/layout.tsx
ReactServerComponentsError:

You have a Server Component that imports next/router. Use next/navigation instead.

Import trace:
  ./app/layout.tsx

如果我删除useRouter并使用useNavigation,则会得到以下内容

Error: (0 , next_navigation__WEBPACK_IMPORTED_MODULE_2__.useNavigation) is not a function

Source
app/layout.tsx (18:30) @ useNavigation

  16 | children: React.ReactNode
  17 | }) {
> 18 | const router = useNavigation()
     |                            ^
  19 | 
  20 | const excludeHeader = router.pathname.startsWith('/admin')

如果我在文件的顶部添加使用客户端,我得到以下错误

You are attempting to export "metadata" from a component marked with "use client", which is disallowed. Either remove the export, or the "use client" directive. Read more: https://beta.nextjs.org/docs/api-reference/metadata

    ,-[/Users/veerpratap/Desktop/nodejs-projects/my-Next-apps/product-reviews/app/layout.tsx:5:1]
  5 | import MainHeader from './layout/main-header'
  6 | const inter = Inter({ subsets: ['latin'] })
  7 | 
  8 | export const metadata = {
    :              ^^^^^^^^
  9 |   title: 'Create Next App',
 10 |   description: 'Generated by create next app',
 11 | }

我可以解决这个错误的任何方法

hs1ihplo

hs1ihplo1#

这对我很有效

import { usePathname } from "next/navigation";
const pathname = usePathname();

useRouter from next/navigation不再导出pathname等,如路由器事件部分之前的链接文档所述

相关问题