重定向到 Next.js 應用程式資料夾中的 404 Not Found 頁面:逐步指南
P粉553428780
P粉553428780 2023-11-03 19:55:27

例如,我們曾經使用 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粉553428780
P粉553428780

全部回覆(1)
P粉805922437

根據文檔,您可以使用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 
Actual Data
; }
// app/user/not-found.js

export default function NotFound() {
  return 

404 Not Found

}

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

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!