【问题标题】:Redirect to 404 Page in Server Component Functions in Next 13在 Next 13 中的服务器组件功能中重定向到 404 页面
【发布时间】:2022-11-07 18:35:11
【问题描述】:

我们曾经使用例如getServerSideProps 重定向到位于pages 目录下的组件中的404 页面,如下所示。在新版本中,我们拥有服务器组件功能。由于getServerSideProps 没有在那里使用,这些组件如何重定向到 404 页面?

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

【问题讨论】:

    标签: javascript reactjs next.js


    【解决方案1】:

    根据文档,您可以使用如下notFound() 函数,它将呈现位于app/feed/not-found.tsx 中的not-found.js 文件。

    // app/user/[id]/page.js
    
    import { notFound } from 'next/navigation';
    
    async function fetchUsers(id) {
      const res = await fetch('https://...');
      return res.json();
    }
    
    export default async function Profile({ params }) {
      const user = await fetchUser(params.id);
    
      if (!user) {
        notFound();
      }
    
      return <div>Actual Data</div>
    
    
    // app/feed/not-found.tsx
    
    export default function NotFound() {
      return "Couldn't find requested resource"
    }
    

    【讨论】:

      猜你喜欢
      • 2013-01-28
      • 1970-01-01
      • 2022-11-20
      • 2021-11-24
      • 1970-01-01
      • 2020-04-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多