Next.js 文档提到了两种访问 router
对象的方法:useRouter
用于功能组件,withRouter
用于基于类的组件。
但是,它没有提到我遇到过几次的 Router
对象,如下所示,例如:
import Router from 'next/router'
Router.push("/")
以这种方式使用 Router
是否正确?为什么 Next.js 文档没有提到它?
最佳答案
我想 而不是 的主要建议是直接从对象本身使用 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
中,它会起作用……但这很笨拙,将来您可能会遇到问题。useRouter
和 withRouter
都是 Next.js 解决这个问题的方法。它们都是构建的,因此它们可以与 SSR 和 CSR 一起使用。所以我的建议是只使用其中之一,它们效果很好🙂。
关于next.js - 从 'next/router' 导入路由器可以吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64325145/