首頁  >  問答  >  主體

重定向到 Next.js 應用程式資料夾中的 404 Not Found 頁面:逐步指南

例如,我們曾經使用 getServerSideProps 來重定向到頁面元件中的 404 頁面,如下所示:

// pages/index.js

export async function getServerSideProps(context) {
  const placeId = context.params.placeId;
  const places = await getPlace(placeId);

  if (!places.length) { 
   return {
     notFound: true,
   }
  }

  return {
    props: {
      places[0],
    },
  };

透過 Next.js 13app 目錄,我們有了伺服器元件。 getServerSideProps 不再使用時如何重定向到 404 頁面?

P粉553428780P粉553428780321 天前589

全部回覆(1)我來回復

  • P粉805922437

    P粉8059224372023-11-04 14:17:20

    根據文檔,您可以使用notFound( ) 函數如下所示,它會渲染對應的not-found.js 文件:

    // app/user/page.js
    
    import { notFound } from 'next/navigation';
    
    export default async function Profile({ params }) {
      const res = await fetch(`/user/${params.id}`);
      if (!res.ok) {
        notFound();
      }
      return <div>Actual Data</div>;
    }
    
    // app/user/not-found.js
    
    export default function NotFound() {
      return <p>404 Not Found</p>
    }
    

    如果沒有 app/user/not-found.js 文件,則使用 app/not-found.js。如果沒有 app/not-found.js,它將使用 Next.js 給出的預設值。

    回覆
    0
  • 取消回覆