从Next.js的app文件夹中的服务器组件重定向至404页面

jm2pwxwz  于 2023-05-06  发布在  其他
关注(0)|答案(1)|浏览(110)

例如,我们使用getServerSideProps重定向到页面组件中的404页面。在新版本中,我们有服务器组件功能。如何重定向到404页面是完成的,因为getServerSideProps不再使用?

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

rur96b6h1#

根据文档,您可以使用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>
}

相关问题