如何解决如何访问 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 route
的身份访问 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>
);
};
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。