NextJS:如何检查当前URL是否为主页?[副本]

gpfsuwkq  于 2023-05-06  发布在  其他
关注(0)|答案(1)|浏览(173)

此问题已在此处有答案

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不是主页,则将文章摘录(初始化)分配为元描述。

093gszye

093gszye1#

如果您尝试在服务器端呈现的组件中使用useRouter,则会出现此错误。要解决此错误,您需要确保组件仅在客户端渲染
一种方法是使用next/dynamic的dynamic import函数在客户端异步加载组件。

import dynamic from 'next/dynamic';

    const DynamicComponent = dynamic(() => import('../components/MyComponent'), {
      ssr: false, // set ssr to false to render only on the client-side
    });

并像通常返回jsx那样正常呈现它:

return (   
          <DynamicComponent /> 
      );

或者,如果你想在服务器端呈现这个组件**,使用getServerSideProps**,如下所示:

export async function getServerSideProps(ctx) {
      const isHome = ctx.req.url === '/';

      return {
        props: {
          isHome
        }
      };
    }

然后像这样使用isHomeprop:

const HomePage = ({ isHome })=> (
    <>
      { isHome ? <h1>Welcome to the home page!</h1>: <h1>This is not the home page.</h1>}
    </>
  )

  export default HomePage;

相关问题