【问题标题】:Implementing i18n with Dynamic Routing on NextJs [duplicate]在 NextJs 上使用动态路由实现 i18n [重复]
【发布时间】:2022-08-10 07:32:36
【问题描述】:

我正在使用 Next.js 实现动态路由和 i18n。我的应用包含 2 个语言环境:en-USes-MX。我正在尝试生成以下路线:

  • /blog/posts/[id]
  • /es-MX/blog/posts/[id]

使用默认语言环境 (en-US),我的链接指向 /blog/posts/id,我可以导航到任何 ID;例如:/blog/posts/1 没有任何问题。但是,当我切换区域设置时,我的链接现在指向路由 /es-MX/blog/posts/1,这反过来会导致 404 错误 - 未找到。

我的 slug 目录由结构 pages/blog/posts/[id].js 组成,在这个文件中我使用 getStaticPaths 生成上述语言环境的路径:

export const getStaticPaths({locales}) => {
   const res = await fetch(`${server}/api/posts`);
   const posts = await res.json();

   const ids = posts.map((post) => post.id);
   const paths = ids.map((id) => ({
      params: {id: id.toString(), locale: \'en-US\' },
      params: {id: id.toString(), locale: \'es-MX\' },
   }));

   return {
       paths,
       fallback: false,
   };
}

我打算根据当前语言环境从 api 中提取帖子翻译。除了这条路线之外,应用程序中的所有其他路线(包括应用程序中的所有其他路线)都按预期工作。我错过了什么?

标签: dynamic routes next.js internationalization


【解决方案1】:

您遇到的问题是您在params 内返回locale,这是错误的,locale 应该在params 之外,因为它可以通过context.locale 而不是context.params.locale 访问, 它适用于defaultLocale,因为这是getStaticPathslocales 的默认行为,请阅读此here 的更多信息。

最好像下面这样重新修改getStaticPaths 以避免params 出现问题:

export const getStaticPaths = async ({ locales }) => {
  const res = await fetch(`${server}/api/posts`);
  const posts = await res.json();

  const ids = posts.map((post) => post.id);
  const paths = ids
    .map((id) =>
      locales.map((locale) => ({
        params: { id: id.toString() },
        locale, //locale should not be inside `params`
      }))
    )
    .flat(); // to avoid nested arrays

  return {
    paths,
    fallback: false,
  };
};

【讨论】:

    猜你喜欢
    • 2022-07-08
    • 2023-03-03
    • 1970-01-01
    • 2020-05-21
    • 1970-01-01
    • 2023-02-11
    • 2020-09-08
    • 2021-08-12
    • 2020-08-25
    相关资源
    最近更新 更多