简体   繁体   English

如何在 Next js 中呈现 static 客户端呈现页面中的错误 404 页面?

[英]How do I render Error 404 page in a static client side rendered page in Next js?

import { onAuthStateChanged } from "firebase/auth";
import Link from "next/link";
import { useRouter } from "next/router";
import { useEffect, useState } from "react";
import { auth } from "../../lib/firebase";

export default function Username() {
  const [context, setContext] = useState();
  const [isLoading, setIsLoading] = useState(true);
  const router = useRouter();
  useEffect(() => {
    onAuthStateChanged(auth, (data) => {
      if (data) {
        setContext(auth);
        setIsLoading(false);
      } else {
        setIsLoading(true);
      }
    });
  }, [router.query?.message]);
    return (
      <div className="username-main-container">
        {!isLoading ? (
          <div className="username-container">
            <div className="user-img-container">
              <img
                src={context.currentUser?.photoURL}
                alt={context.currentUser?.displayName}
                className="user-img"
              />
            </div>
            <div className="information-container">
              <h1>{context?.currentUser?.displayName}</h1>
              <Link href={`/${router.query?.username}/public`}>
                <button className="btn">Send Annonymous Messages</button>
              </Link>
            </div>
          </div>
        ) : null}
      </div>
    );
}

I want to render a custom 404 page when the user accidentally goes to an invalid URL but instead, this code just loads the data of the currently signed-in user.当用户不小心转到无效的 URL 时,我想呈现自定义 404 页面,但此代码只是加载当前登录用户的数据。

As you can see this is a static page so I want the solution for static pages.如您所见,这是一个 static 页面,所以我想要 static 页面的解决方案。 I know you can set notFound: true in SSR or set the fallback: false in ISR pages but I am looking for a solution for completely static pages.我知道您可以在 SSR 中设置notFound: true或在 ISR 页面中设置fallback: false但我正在寻找完全 static 页面的解决方案。

Thank you.谢谢你。

 // pages/404.js export default function Custom404() { return <h1>404 - Page Not Found</h1> }

This is for custom error This is not necessary but if you want custom error do this nextjs will automatically do this for you if someone go to unknown page this error will popup you can try that on development.这是针对自定义错误这不是必需的,但是如果您想要自定义错误,如果有人 go 到未知页面,nextjs 会自动为您执行此操作,此错误将弹出,您可以在开发中尝试。

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

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