从“next/router”导入路由器可以吗?

fre*_*erk 21 router next.js next-router

Next.js 文档提到了两种访问router对象的方法:useRouter功能组件和withRouter基于类的组件。

然而,它没有提到我几次遇到的东西,即Router按如下方式访问的对象,例如:

import Router from 'next/router'

Router.push("/")
Run Code Online (Sandbox Code Playgroud)

Router这样使用正确吗?为什么 Next.js 文档没有提到它?

小智 19

我想主要建议不要直接从对象本身使用 Router.push() 或 Router.pathname 是因为 Next.js 为应用程序提供服务的方式。当您尝试执行以下操作时:

import Router from 'next/router';

const HomePage = () => {
  console.log(Router.pathname);

  return (
    <div>hi</div>
  )
}
Run Code Online (Sandbox Code Playgroud)

您将收到一条错误消息:You should only use "next/router" inside the client side of your app。这是因为 next/router 与 SSR 的配合方式。

不过,您可以将其放入 an 中useEffect,它会起作用...但这很糟糕,您将来可能会遇到问题。

useRouter都是withRouterNext.js 针对这个问题的解决方案。它们都是构建的,因此可以与 SSR 和 CSR 一起使用。所以我的建议是只使用其中之一,它们效果很好。

  • 另请参阅 https://github.com/vercel/next.js/discussions/18522:“...对于并发功能很重要...” (5认同)