Published 2022-05-06

Next.js - Custom 404

关于 404

http status 404

reP4tT

自定义 404 页面

创建404.js文件,并在其中定义自定义 404 页面。

import Link from 'next/link'

const MyCustom404Page = (props) => {
  return (
    <div
      style={{
        marginTop: 100,
        display: 'flex',
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'center'
      }}
    >
      <h1>404</h1>
      <h2>
        <Link href="/" style={{color: 'blue', textDecoration: 'underline'}}>
          Go To Home Page
        </Link>
      </h2>
      <p>Sorry, the content you are looking for cuould not be found.</p>
    </div>
  )
}

export default MyCustom404Page

检查结果

vr7Yoj

动态渲染 404 页面

next.js 允许通过getStaticPropsgetServerSideProps请求数据并自定义 404 页面。

import Link from 'next/link'

const MyCustom404Page = (props) => {
  return (
    <div
      style={{
        marginTop: 100,
        display: 'flex',
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'center'
      }}
    >
      <h1>404 - Page Not Found</h1>
      <h2>
        <Link href="/" style={{color: 'blue', textDecoration: 'underline'}}>
          Go To Home Page
        </Link>
      </h2>
      <p>Or check out our latest news:</p>
      <hr />
      <ul>
        {posts.map((articles) => (
          <li>{/* article title and href here */}</li>
        ))}
      </ul>
    </div>
  )
}

export async function getStaticProps() {
  // Call an external API endpoint to get posts.
  const res = await fetch('YOUR_API_URL')
  const posts = await res.json()

  return {
    props: {
      posts
    },
    // Next.js will attempt to re-generate the page:
    // - When a request comes in
    // - At most once every second
    revalidate: 60
  }
}

export default MyCustom404Page