登录  /  注册
重定向到 Next.js 应用程序文件夹中的 404 Not Found 页面:分步指南
P粉553428780
ArrayP粉553428780 2023-11-03 19:55:27
[React讨论组]

例如,我们曾经使用 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 给出的默认值。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 技术文章
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2023 //m.sbmmt.com/ All Rights Reserved | 苏州跃动光标网络科技有限公司 | 苏ICP备2020058653号-1

 | 本站CDN由 数掘科技 提供

登录PHP中文网,和优秀的人一起学习!
全站2000+教程免费学