我在 nextjs 中使用新的应用程序 Router 。获取错误:useRouter 仅适用于客户端组件。添加“use client”指令来使用它

Vee*_*tap 11 next.js

./app/layout.tsx
ReactServerComponentsError:

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

Import trace:
  ./app/layout.tsx
Run Code Online (Sandbox Code Playgroud)

如果我删除 use 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')
Run Code Online (Sandbox Code Playgroud)

如果我在文件顶部添加 use client ,我会收到以下错误

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 | }
Run Code Online (Sandbox Code Playgroud)

有什么方法可以解决这个错误

Can*_*Can 5

这对我有用,

import { usePathname } from "next/navigation";
const pathname = usePathname();
Run Code Online (Sandbox Code Playgroud)

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


归档时间:

查看次数:

14667 次

最近记录:

1 年,9 月 前