如何在 Remix 中创建自定义样式的 404 页面

Bob*_*bby 7 remix.run

您好,我如何在 Remix 中设计和创建自定义 404 页面。

我想在识别路径时用我自己的内容覆盖当前的 404 页面。

在此输入图像描述

Dav*_*rte 9

太长了;

创建一个routes/$.jsx文件。您可以选择在该路由中添加此加载程序,以获得 HTTP 404 状态代码。

export const loader = () => {
  return json(null, { status: 404 });
};
Run Code Online (Sandbox Code Playgroud)

链接到文档

更广阔的视野

您应该在 3 种类型的错误上显示自定义 ui:

  • 意外错误,例如Cannot read properties of undefinedErrorBoundary in root.tsx
  • 自定义逻辑等预期错误return json({ errors: [{code: "unpaid", message: "user didnt pay"}] })CatchBoundaryroot.tsx
  • 404(Splat 路线 $.tsxroutes/

如果您认为这会给用户带来更好的用户体验(例如在选项卡或文件夹中),您还可以为每个嵌套路由定义一个 ErrorBoundary/CatchBoundary。


小智 4

您可以编辑CatchBoundaryin root.tsx/root.tsx并返回您想要渲染的任何内容。

export function CatchBoundary() {
  const caught = useCatch();

  return (
    <html>
      <head>
        <title>Oops!</title>
        <Meta />
        <Links />
      </head>
      <body>
        <h1>
          {caught.status} {caught.statusText}
        </h1>
        <Scripts />
      </body>
    </html>
  );
}
Run Code Online (Sandbox Code Playgroud)

相关文档在这里:https://remix.run/docs/en/v1/guides/not-found#root-catch-boundary