全书目录

第五篇:Next.js 完全指南 —— 商业综合体宇宙

第十章:错误、空状态、404 —— 商业综合体必须有应急预案

1 分钟 154 字 第 121 / 962 个阅读单元

真实系统不会永远成功。
Next.js 把很多“故障预案”做成了文件约定。

#1. error.tsx —— 某个区域炸了,先把这一层兜住
tsx
// app/products/error.tsx
'use client';

export default function Error({
  error,
  reset,
}: {
  error: Error;
  reset: () => void;
}) {
  return (
    <div>
      <p>商品区加载失败:{error.message}</p>
      <button onClick={() => reset()}>重试</button>
    </div>
  );
}

注意:error.tsx 本身要是 Client Component,因为它要处理交互式恢复。

#2. not-found.tsx —— 店铺号不存在
tsx
// app/products/not-found.tsx
export default function NotFound() {
  return <h1>你访问的商品不存在</h1>;
}

配合页面里主动触发:

tsx
import { notFound } from 'next/navigation';

export default async function ProductPage({
  params,
}: {
  params: Promise<{ slug: string }>;
}) {
  const { slug } = await params;
  const product = null;

  if (!product) notFound();

  return <div>{slug}</div>;
}