此问题已在此处有答案:
How to get the current pathname in the app directory of Next.js 13?(1个答案)
6天前关闭。
新的NextJS。
我想检查当前URL是否是主页。
如果我用
import { useRouter } from "next/router";
const router = useRouter();
const is_home = (router.pathname === '');
我得到一个前端错误You have a Server Component that imports next/router. Use next/navigation instead.
如果我改变import { useRouter } from "next/router";
到import { useRouter } from "next/navigation";
我得到一个终端错误Error: useRouter only works in Client Components. Add the "use client" directive at the top of the file to use it.
如果我将"use client"
添加到文件的顶部,终端错误就会消失,但router.pathname
中的pathname
在VS Code中会突出显示为红色,并且悬停错误会显示为Property 'pathname' does not exist on type 'AppRouterInstance'.ts(2339)..
我找不到next/navigation
的任何文档,就像next/router
一样。
有没有更简单的方法来检查主页?
我想为主页分配一个默认的 meta描述,如果当前URL不是主页,则将文章摘录(初始化)分配为元描述。
1条答案
按热度按时间093gszye1#
如果您尝试在服务器端呈现的组件中使用useRouter,则会出现此错误。要解决此错误,您需要确保组件仅在客户端渲染。
一种方法是使用next/dynamic的dynamic import函数在客户端异步加载组件。
并像通常返回jsx那样正常呈现它:
或者,如果你想在服务器端呈现这个组件**,使用getServerSideProps**,如下所示:
然后像这样使用isHomeprop: