Weiterleitung zur Seite „404 nicht gefunden' im Next.js-Anwendungsordner: Schritt-für-Schritt-Anleitung
P粉553428780
P粉553428780 2023-11-03 19:55:27
0
1
712

Zum Beispiel haben wir einmal getServerSideProps verwendet, um in der Seitenkomponente wie folgt auf eine 404-Seite umzuleiten:

// 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],
    },
  };

Mit den Next.js-Verzeichnissen 13 und app haben wir die Serverkomponente. 13app 目录,我们有了服务器组件。 getServerSideProps Wie kann ich zur 404-Seite umleiten, wenn ich sie nicht mehr verwende?

P粉553428780
P粉553428780

Antworte allen(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 <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 给出的默认值。

Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage