Par exemple, nous avons déjà utilisé getServerSideProps
pour rediriger vers une page 404 dans le composant page comme ceci?:
// 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], }, };
Avec les répertoires Next.js 13
et app
, nous avons le composant serveur. 13
和 app
目錄,我們有了服務(wù)器組件。 getServerSideProps
Comment rediriger vers une page 404 lorsqu'il n'est plus utilisé ?
D'après la documentation, vous pouvez utiliser le fichier notFound( )
函數(shù)如下所示,它會渲染相應(yīng)的 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> }
Sans app/user/not-found.js
文件,則使用 app/not-found.js
。如果沒有 app/not-found.js
, il utilisera la valeur par défaut donnée par Next.js.