我已经决定使用i18next
和react-i18next
来翻译我的React应用程序。一切正常,直到我想使用字符串而不是键。我的应用程序告诉我它无法将丢失的键保存到translation.json文件中,因为找不到它们see console errors。即使文件存在see tree。我也得到this messages in console。我认为问题很简单,但是我还没有解决的办法,我希望这里有经验的人,可以帮助我摆脱这个问题。
我的i18next配置:
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import Backend from 'i18next-xhr-backend';
import LanguageDetector from 'i18next-browser-languagedetector';
i18n
.use(Backend)
.use(LanguageDetector)
.use(initReactI18next)
.init({
react: {
useSuspense: false, // <---- this will do the magic
wait: true
},
backend: {
loadPath: '/locales/{{lng}}/{{ns}}.json',
addPath: '/locales/add/{{lng}}/{{ns}}',
allowMultiLoading: true,
},
lng: 'en',
nsSeparator: false,
keySeparator: false,
fallbackLng: 'en',
fallbackNS: 'translation',
debug: true,
ns: ["translation", "header", "random"],
defaultNS: "translation",
saveMissing: true
});
i18n
.loadNamespaces(['translation','header'])
.then(() => {});
i18n.on('missingKey', function(lngs, namespace, key, res) {console.log(key)});
export default i18n;
我的index.js文件:
import React from 'react';
import i18n from './i18n/i18n';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';
import * as serviceWorker from './registerServiceWorker';
import {I18nextProvider} from 'react-i18next';
ReactDOM.render(
<I18nextProvider i18n={i18n}>
<App/>
</I18nextProvider>,
document.getElementById('root')
);
serviceWorker.register();
我使用这样的键:
{t('Need to save this text')}
为什么要两次加载名称空间?由于您已经在init中定义了它们,因此可以避免之后加载。
可能是因为您试图在初始化完成之前加载名称空间。
而且,您似乎错过了.json
键中的addPath
扩展名