首页 > 解决方案 > 在 React 中设置 i18next 我做错了什么?收到“i18next::translator: missingKey”错误

问题描述

在我src的文件夹中,我创建了一个名为 的文件夹i18n,其中包含这三个文件

en.json
es.json
pl.json

这就是他们的样子:

{
  "selectAction": "Select Action",
  "workflow": "Workflow",
  "details": "Details"
}

src文件夹中,我还添加了这个名为i18n.js

import i18n from 'i18next'
import LanguageDetector from "i18next-browser-languagedetector"
import { initReactI18next } from 'react-i18next'
// import Backend from "i18next-xhr-backend";
// import XHR from 'i18next-xhr-backend'
import languageEn from './i18n/en.json'
import languageEs from './i18n/es.json'
import languagePl from './i18n/pl.json'

i18n
  // .use(Backend)
  // .use(XHR)
  .use(LanguageDetector)
  .use(initReactI18next)
  .init({
    resources: {
      en: languageEn,
      es: languageEs,
      pl: languagePl
    },
    lng: "es",
    fallbackLng: "en",
    debug: true,
    keySeparator: ".",
    interpolation: {
      escapeValue: false,
    }
  });

console.log(i18n.languages)

export default i18n;

我在 src 根目录中的 index.js 文件如下所示:

// import statements are omitted, but I am importing I18NextProvider and i18n
ReactDOM.render(
  <I18nextProvider i18n={i18n}>
    <App />
  </I18nextProvider>
  document.getElementById('root')
);

最后,在我的应用程序的某个地方,我有这个:

// Other imports omitted
import { useTranslation } from 'react-i18next';

const DetailsPlaceholder = () => {
  const { t } = useTranslation();

  return (
     <h4 className="zero-state-section-text">{t('selectAction')}</h4>
  );
};

export default DetailsPlaceholder;

当我尝试加载页面时,我看到键 'selectAction' 作为文本(而不是真实文本),并且记录了这个错误:

i18next::translator: missingKey es translation selectAction selectAction

标签: reactjsinternationalizationi18next

解决方案


translation所有资源文件都应在key下存储字符串(如快速入门中的react-i18next):

{
  "translation": {
    "selectAction": "Select Action",
    "workflow": "Workflow",
    "details": "Details"
  }
}

这是一个带有重现错误和固定配置的存储库:
https ://github.com/terales/reproduce-react-i18next-missingkey-error


推荐阅读