简体   繁体   English

如何访问 Next.JS 自定义 404 页面上的当前路由?

[英]How do I access the current route on a Next.JS custom 404 page?

I have a custom 404 page in my Next.JS app (404.js).我的 Next.JS 应用程序 (404.js) 中有一个自定义 404 页面。 On the page, I'd like to display a message like The route <strong>/not-a-route</strong> does not exist , however when using Next.js's useRouter() and router.pathname , the router thinks I'm on /404 and instead displays The route <strong>/404</strong> does not exist .在页面上,我想显示一条消息,如The route <strong>/not-a-route</strong> does not exist ,但是当使用 Next.js 的useRouter()router.pathname时,路由器认为我'm on /404而不是显示The route <strong>/404</strong> does not exist How do I access the actual route I'm on in a custom 404 page?如何在自定义 404 页面中访问我所在的实际路线?

export const NotFound: React.FC = () => {
  const router = useRouter();
  console.log(router.pathname) // prints /404
  return (
    <Layout title='Oops! Something went wrong!'>
      <div className={styles.container}>
        <h1>Oops! Something went wrong!</h1>
          <p>
            The route <strong>{router.pathname}</strong> does not exist.
          </p>
      </div>
    </Layout>
  );
};

You can access the redirected route as router.asPath .您可以通过router.asPath访问redirected route Try:尝试:

import {useRouter} from 'next/router'
export const NotFound: React.FC = () => {
  const router = useRouter();
  console.log(router.asPath)
  return (
    <Layout title='Oops! Something went wrong!'>
      <div className={styles.container}>
        <h1>Oops! Something went wrong!</h1>
          <p>
            The route <strong>{router.asPath}</strong> does not exist.
          </p>
      </div>
    </Layout>
  );
};

You can access the original route by accessing router.asPath , where router is returned from useRouter() hook.您可以通过访问router.asPath来访问原始路由,其中router是从useRouter()钩子返回的。 Beware though, if you don't specify getStaticProps , router.asPath will return "/404" on server side, causing hydration error.但是请注意,如果您不指定getStaticPropsrouter.asPath将在服务器端返回"/404" ,导致水合作用错误。

So to make use of router.asPath you will have to create getStaticProps function that doesn't return anything因此,要使用router.asPath ,您必须创建不返回任何内容的getStaticProps function

import { useRouter } from 'next/router';

import type { GetStaticProps } from 'next';

type Props = Record<string, never>;

export const getStaticProps: GetStaticProps<Props> = () => {
  return { props: {} };
};

export default function PageNotFound() {
  const router = useRouter();

  return (
    <p>
      The requested page <strong>{router.asPath}</strong> could not be found.
    </p>
  );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM