简体   繁体   English

如何在 nextjs 应用程序的动态路由页面上添加 next-i18next 翻译?

[英]How to add next-i18next translation on a dynamically routed page in a nextjs application?

I have a dynamically routed page in Nextjs (v10.1.3) /my-translation/[id] , I'd like to use next-i18next (v8.1.3) package to translate this page.我在 Nextjs (v10.1.3) /my-translation/[id]中有一个动态路由页面,我想使用 next-i18next (v8.1.3) package 来翻译这个页面。

I tried using 2 folder structure in Nextjs, they both give the same error that I can not grasp.我尝试在 Nextjs 中使用 2 个文件夹结构,它们都给出了我无法理解的相同错误。

  • pages/translated-page/[id]/index.tsx pages/translated-page/[id]/index.tsx
  • pages/translated-page/[id].tsx pages/translated-page/[id].tsx

However, if I change dynamic routing to static, the translation works.但是,如果我将动态路由更改为 static,则翻译工作正常。

Example for working folder structure:工作文件夹结构示例:

  • pages/translated-page/id.tsx页面/翻译页面/id.tsx
import { serverSideTranslations } from "next-i18next/serverSideTranslations";
import { useRouter } from "next/router";
import { useTranslation } from "next-i18next";

const TranslatedPage = () => {
  const { t } = useTranslation("my-translation");
  const router = useRouter();
  const { id } = router.query;

  return (
      <div>
         {t("existing-translation-key-from-my-translation-json")}
      </div>
  );
};

export const getStaticProps = async ({ locale }) => ({
  props: {
    fallback: true,
    paths: ["/translated-page/id", { params: { id: "" } }],
    ...(await serverSideTranslations(locale, ["my-translation"])),
  },
});

export default TranslatedPage;

I get the error below for the dynamic route, I could not grasp from the provided link what I did wrong.我收到以下动态路线的错误,我无法从提供的链接中了解我做错了什么。

Server Error Error: getStaticPaths is required for dynamic SSG pages and is missing for '/translated-page/[id]'.服务器错误错误:动态 SSG 页面需要 getStaticPaths,而“/translated-page/[id]”缺少 getStaticPaths。 Read more: https://nextjs.org/docs/messages/invalid-getstaticpaths-value This error happened while generating the page.阅读更多: https://nextjs.org/docs/messages/invalid-getstaticpaths-value生成页面时发生此错误。 Any console logs will be displayed in the terminal window.任何控制台日志都将显示在终端 window 中。 Call Stack renderToHTML file:///C:/projects/my-project.io/web-apps/my-project/node_modules/next/dist/next-server/server/render.js (21:2118) file:///C:/projects/my-project.io/web-apps/my-project/node_modules/next/dist/next-server/server/next-server.js (112:126) __wrapper file:///C:/projects/my-project.io/web-apps/my-project/node_modules/next/dist/lib/coalesced-function.js (1:341) file:///C:/projects/my-project.io/web-apps/my-project/node_modules/next/dist/lib/coalesced-function.js (1:377) DevServer.renderToHTMLWithComponents file:///C:/projects/my-project.io/web-apps/my-project/node_modules/next/dist/next-server/server/next-server.js (137:120) runMicrotasks processTicksAndRejections internal/process/task_queues.js (93:5) async DevServer.renderToHTML file:///C:/projects/my-project.io/web-apps/my-project/node_modules/next/dist/next-server/server/next-server.js (138:923) async DevServer.renderToHTML file:///C:/projects/my-project.io/web-apps/my-project/node_modules/next/dist/server/next-de调用堆栈 renderToHTML file:///C:/projects/my-project.io/web-apps/my-project/node_modules/next/dist/next-server/server/render.js (21:2118) file:/ //C:/projects/my-project.io/web-apps/my-project/node_modules/next/dist/next-server/server/next-server.js (112:126) __wrapper file:///C :/projects/my-project.io/web-apps/my-project/node_modules/next/dist/lib/coalesced-function.js (1:341) file:///C:/projects/my-project. io/web-apps/my-project/node_modules/next/dist/lib/coalesced-function.js (1:377) DevServer.renderToHTMLWithComponents file:///C:/projects/my-project.io/web-apps /my-project/node_modules/next/dist/next-server/server/next-server.js (137:120) runMicrotasks processTicksAndRejections internal/process/task_queues.js (93:5) async DevServer.renderToHTML file:/// C:/projects/my-project.io/web-apps/my-project/node_modules/next/dist/next-server/server/next-server.js (138:923) async DevServer.renderToHTML file:/// C:/projects/my-project.io/web-apps/my-project/node_modules/next/dist/server/next-de v-server.js (35:578) async DevServer.render file:///C:/projects/my-project.io/web-apps/my-project/node_modules/next/dist/next-server/server/next-server.js (75:236) async Object.fn file:///C:/projects/my-project.io/web-apps/my-project/node_modules/next/dist/next-server/server/next-server.js (59:580) async Router.execute file:///C:/projects/my-project.io/web-apps/my-project/node_modules/next/dist/next-server/server/router.js (25:67) async DevServer.run file:///C:/projects/my-project.io/web-apps/my-project/node_modules/next/dist/next-server/server/next-server.js (69:1042) async DevServer.handleRequest file:///C:/projects/my-project.io/web-apps/my-project/node_modules/next/dist/next-server/server/next-server.js (34:504) v-server.js (35:578) async DevServer.render file:///C:/projects/my-project.io/web-apps/my-project/node_modules/next/dist/next-server/server/ next-server.js (75:236) async Object.fn file:///C:/projects/my-project.io/web-apps/my-project/node_modules/next/dist/next-server/server/ next-server.js (59:580) async Router.execute file:///C:/projects/my-project.io/web-apps/my-project/node_modules/next/dist/next-server/server/ router.js (25:67) async DevServer.run file:///C:/projects/my-project.io/web-apps/my-project/node_modules/next/dist/next-server/server/next- server.js (69:1042) async DevServer.handleRequest file:///C:/projects/my-project.io/web-apps/my-project/node_modules/next/dist/next-server/server/next- server.js (34:504)

I got it working by adding getStaticPaths function我通过添加getStaticPaths function 让它工作了

  export const getStaticProps = async ({ locale }) => ({
    props: {
      ...(await serverSideTranslations(locale, ["my-translation"])),
    },
  });
    
  export const getStaticPaths = async () => {
    return {
      paths: ["/my-translation/id"],
      fallback: true,
    };
  };

I was able to solve this by adding the locale to the getStaticPaths function.我能够通过将语言环境添加到 getStaticPaths function 来解决这个问题。

Considering your id is your file parameter ( [id].js ) what worked form me would look like this:考虑到您的 id 是您的文件参数( [id].js ),我的工作方式如下所示:


import { serverSideTranslations } from "next-i18next/serverSideTranslations";
import { useRouter } from "next/router";
import { useTranslation } from "next-i18next";


const TranslatedPage = () => {
  const { t } = useTranslation("my-translation");
  const router = useRouter();
  const { id } = router.query;

  return (
      <div>
         {t("existing-translation-key-from-my-translation-json")}
      </div>
  );
};

export const getStaticPaths = async () => {
    return {
      paths: [
      { params: { type: "id" }, locale: "es" },
      { params: { type: "id" }, locale: "en" },
      ]
      fallback: true,
    };
  };

export async function getStaticProps(context) {
  return {
    props: {
      params: context.params,
      ...(await serverSideTranslations(context.locale, ["my-translation"])),
    },
  }
}

After that, you don't need to have two folders, just keep pages/translated-page/[id].tsx (considering you'll only have dynamic routes).之后,您不需要有两个文件夹,只需保留 pages/translated-page/[id].tsx (考虑到您只有动态路由)。

In case you have a lot of routes or languages, consider running a small function to simply add {locale:lang} to all your paths.如果您有很多路线或语言,请考虑运行一个小型 function 以简单地将 {locale:lang} 添加到所有路径。

You need to add locale keyword to each path in getStaticPaths.您需要将语言环境关键字添加到 getStaticPaths 中的每个路径。

export async function getStaticPaths({ locales }) {
  const categories = [{id:"id1"},{id:"1d2"}];
  const paths = categories.flatMap((category) => {
    return locales.map((locale) => {
      return {
        params: {
          type: category.id,
        },
        locale: locale,
      };
    });
  });
  return {
    paths: paths,
    fallback: true,
  };
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM