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

詹姆斯怀特利

我的 Next.JS 应用程序 (404.js) 中有一个自定义 404 页面。在页面上,我想显示类似 的消息The route <strong>/not-a-route</strong> does not exist,但是当使用 Next.js 的useRouter()和 时router.pathname,路由器认为我已打开/404,而是显示The route <strong>/404</strong> does not exist如何在自定义 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>
  );
};
思南崖曼

您可以访问redirected routeas router.asPath尝试:

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>
  );
};

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何制作自定义 404 页面?

如何在 Next JS 中导入自定义字体?

Next.js 10 +子路由,如何在服务器端的自定义应用中访问区域设置

如何自定义404错误页面(Ubuntu Nginx)

Spring MVC:如何返回自定义404错误页面?

如何使用从自定义后端收到的 jwt 令牌在 Next.js 中添加受保护的路由?

具有自定义快递服务器的Next.js重新呈现所有自定义路由

如何在液体shopify模板中隐藏自定义滑轨404页面上的页脚

Next.js - 如何在 404 页面上隐藏导航和页脚组件?

如何使用自定义服务器 (Nest.js) 构建生产 Next.js

Next.js自定义配置在索引上产生404-next-images,next-css,webpack,lquip-loader

实施自定义404错误页面

如何获取角度2中的当前路线自定义数据?

自定义 404 页面上的图像问题,django

刷新自定义404错误页面上的URL

如何使用页面应用程序中的自定义页面更改默认的404错误页面

如何在剃刀页面中重定向到自定义 404 页面

如何在不使用自定义服务器的情况下在Next.js中设置自定义HTTP响应标头?

如何通过在Spring MVC中返回自定义的错误页面来全局处理404异常?

Yii2:如何自定义错误页面,如404和503

如何在Laravel 5.7中创建自定义404页面?

如何在执行 is_ajax_request 函数时在 CODEIGNITER 中自定义 404 页面

如何在Java App Engine上实现自定义404错误页面?

如何在Dropwizard中查看自定义404页面

如何在Angular Project中为自定义404页面设置路线

如何修复自定义 404 页面在 NextJS 中不起作用

如何在php中显示子文件夹的自定义404错误页面?

Next.js-页面无法将GetServerSideProps放入Page组件属性(带有自定义_app.js)

Next Js自定义路线和SSR