【问题标题】:import Router from 'next/router' is it ok?从“下一个/路由器”导入路由器可以吗?
【发布时间】:2021-09-28 12:20:39
【问题描述】:

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

但是,它没有提到我遇到过几次的事情,即Router 对象,如下访问,例如:

import Router from 'next/router'

Router.push("/")

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

【问题讨论】:

标签: next.js router next-router


【解决方案1】:

我想直接从对象本身使用 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 一起工作的方式。

但是,您可以将其放在 useEffect 中,它会起作用...但那很老套,您将来可能会遇到问题。

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

【讨论】:

猜你喜欢
  • 2020-07-30
  • 1970-01-01
  • 2022-01-15
  • 1970-01-01
  • 1970-01-01
  • 2021-02-26
  • 1970-01-01
  • 2019-04-20
相关资源
最近更新 更多