Next.js 如何在 i18n 场景下处理 404 页面

问题

使用 Next.js 框架,app route 模式,404 页面在国际化场景下无法正常使用。

在 Next.js 中的 app route 模式,约定了很多页面的路径,比如 layout.tsxpage.tsx。对于 404 页面,可以使用 not-found.tsx:

tsx 复制代码
import Link from "next/link";

export default function NotFound() {
  return (
    <div>
      <h2>Not Found</h2>
      <p>Could not find requested resource</p>
      <Link href="/">Return Home</Link>
    </div>
  );
}

再说回国际化,国际化方案一般使用动态路由,在 app 目录下创建 [lang] 文件夹。

这样就可以在页面中通过 params 获取到当前语言,然后根据语言加载对应的资源。

ts 复制代码
export default function RootLayout({ children, params: { lang } }) {

那么所有的页面都应该在 [lang] 目录下,包括 404 页面。就像这样 app/[lang]/not-found.tsx

问题来了,这样写的话,输入一个不存在的路径,会显示 Next.js 默认的 404 页面,而不是我们自定义的 404 页面。

解决方案

app/[lang] 目录下创建 [...not_found]/page.tsx 文件,用于捕获所有的 404 页面。

tsx 复制代码
// 从 next/navigation 中导入我们自定义的 notFound 方法
import { notFound } from "next/navigation";

export default function NotFoundCatchAll() {
  notFound();
}

这样就 OK 啦~

但是还有一个问题,notFound 不接收任何 Props,所以我们无法在 404 页面中获取到当前语言。

如果你想对 404 页面的文案做国际化,就还需要再做处理。

很简单,不使用 Next.js 的 notFound 方法,自己写一个 components/notFound.tsx 组件。

tsx 复制代码
export default async function NotFound({ lang }) {
  const { t } = await useTranslation(lang, "not-found");
  return <div>{t("404")}</div>;
}

然后在 app/[lang]/[...not_found]/page.tsx 中使用这个组件。

tsx 复制代码
import NotFound from "@/components/common/not-found";

export default function NotFoundCatchAll({ params: { lng } }) {
  return <NotFound lng={lng} />;
}

中文404页面

英文404页面

至此大功告成,完美解决 Next.js 在国际化场景下的 404 页面问题,可以删掉 app/[lang]/not-found.tsx 文件了。

总结

Next.js 一言难尽。

相关推荐
訾博ZiBo12 小时前
【Vibe Coding】001-前端界面常用布局
前端
软件技术NINI12 小时前
MATLAB疑难诊疗:从调试到优化的全攻略
javascript·css·python·html
IT_陈寒12 小时前
《Redis性能翻倍的7个冷门技巧,90%开发者都不知道!》
前端·人工智能·后端
歪歪10012 小时前
React Native开发Android&IOS流程完整指南
android·开发语言·前端·react native·ios·前端框架
知识分享小能手12 小时前
uni-app 入门学习教程,从入门到精通,uni-app组件 —— 知识点详解与实战案例(4)
前端·javascript·学习·微信小程序·小程序·前端框架·uni-app
ZYMFZ13 小时前
python面向对象
前端·数据库·python
长空任鸟飞_阿康13 小时前
在 Vue 3.5 中优雅地集成 wangEditor,并定制“AI 工具”下拉菜单(总结/润色/翻译)
前端·vue.js·人工智能
lapiii35813 小时前
快速学完React计划(第一天)
前端·react.js·前端框架
liangshanbo121513 小时前
React + TypeScript 企业级编码规范指南
ubuntu·react.js·typescript