简体   繁体   中英

Why is my translations not working with react-i18next?

This is my config file:

i18n.js:

import i18n from 'i18next';
import Backend from 'i18next-xhr-backend';
import detector from "i18next-browser-languagedetector";
import { initReactI18next } from 'react-i18next';

const fallbc = ['en'];
const langArr = ['en', 'de'];

i18n
    .use(detector)
    .use(Backend)
    .use(initReactI18next)
    .init({
        backend: {
            loadPath: '/register/locales/{{lng}}/{{ns}}.json'
        },
        fallck,
        debug: true,
        whitelist: langArr,
        interpolation: {
            escapeValue: false,
        },
        react: {
            wait: true,
        },
    });

export default i18n;

And when I try this:

import i18n from '../i18n';

return (
         <div>
           <button onClick={() => i18n.changeLanguage('de')}>de</button>
           <button onClick={() => i18n.changeLanguage('en')}>en</button>
         </div>
       );

Only English is rendered, the German is not. What am I doing wrong?

Is something wrong with my configuration? I feel that I am really close to resolving this.

i18n.Init is a lazy load function You have to wait for callback has to be called. Else use SyncBackend. Else start app lazy.

Sample:

import i18next from 'i18next';
import SyncBackend from 'i18next-sync-fs-backend';


// working
i18next
  .use(SyncBackend)
  .init({ initImmediate: false });

i18next.t('key'); // -> will return value

Lazy Start:

export default (callback) => {
const instance = i18n
    .use(detector)
    .use(Backend)
    .use(initReactI18next)
    .init({
        backend: {
            loadPath: '/register/locales/{{lng}}/{{ns}}.json'
        },
        fallck,
        debug: true,
        whitelist: langArr,
        interpolation: {
            escapeValue: false,
        },
        react: {
            wait: true,
        },
    },() => callback(instance));
};

import i18nInit from '../i18n';

i18nInit((i18n) =>{
// lazy start here
return (
         <div>
           <button onClick={() => i18n.changeLanguage('de')}>de</button>
           <button onClick={() => i18n.changeLanguage('en')}>en</button>
         </div>
       );

})

More: https://www.i18next.com/overview/configuration-options

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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