8

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

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

import Router from 'next/router'

Router.push("/")

以这种方式使用是否正确Router?为什么 Next.js 文档没有提到它?

4

1 回答 1

6

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

import Router from 'next/router';

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

  return (
    <div>hi</div>
  )
}

您将收到以下错误:You should only use "next/router" inside the client side of your app。这是因为 next/router 与 SSR 一起工作的方式。

但是,您可以将其放入 an 中useEffect,它会起作用……但这很hacky,将来您可能会遇到问题。

两者都是 Next.js 解决这个问题的方法useRouterwithRouter它们都是构建的,因此它们可以与 SSR 和 CSR 一起使用。所以我的建议只是使用其中一种,它们效果很好。

于 2020-10-14T13:07:55.567 回答