React Typescript i18next 缺少密钥错误

React Typescript i18next missing key error

我想为我的项目添加翻译器,但 i18next 显示密钥并且在控制台中出现密钥丢失错误。

import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import Backend from "i18next-http-backend";
import LanguageDetector from "i18next-browser-languagedetector";
import i18next from "i18next";

i18n.use(Backend)
  .use(LanguageDetector)
  .use(initReactI18next)
  .init({
    fallbackLng: "en",
    debug: true,
    interpolation: {
      escapeValue: false,
    },
    backend: {
      loadPath: "./locales/{{lng}}/translation.json",
    },
  });

export default i18n;
import "react-i18next";
import en from "./src/locales/en/translation.json";
import fa from "./src/locales/fa/translation.json";

declare module "react-i18next" {
  interface Resources {
    en: typeof en;
    fa: typeof fa;
  }
}

translation.json是这样的:

{
    "Hello": "Hello World"
}
import { useTranslation } from "react-i18next";

function hello (){

  const { t, i18n } = useTranslation();

  return (
    <div>
      <h1> {t("Hello")}</h1>
    </div>

  );
}

首先将 i18.ts 文件更改为 i18nProvider,然后像这样将代码添加到 useEffect 中

const I18nProvider: React.FunctionComponent = (props) => {
    useEffect(() => {
       i18n.use(Backend)
      .use(LanguageDetector)
      .use(initReactI18next)
      .init({
        fallbackLng: "en",
        debug: true,
        interpolation: {
          escapeValue: false,
        },
        backend: {
          loadPath: "./locales/{{lng}}/translation.json",
        },
      });
 }, []);
  return (
     <Suspense fallback={<h1>Loading ...</h1>}>
    <I18nextProvider i18n={i18n}>{props.children}</I18nextProvider>
     </Suspense>
  );

其次将 i18Provider 添加到您的 _app,如下所示:

const MyApp = ({ Component, pageProps }) => {
  return (
      <I18nProvider>
            <Component {...pageProps} />
      </I18nProvider>
  );
};

export default MyApp;

问题已解决,如果您有同样的问题,请按照下面的例子进行操作。问题将得到解决。请注意,即使文件夹的名称及其位置也应与示例相同。

Link: https://dev.to/adrai/how-to-properly-internationalize-a-react-application-using-i18next-3hdb