我们如何使用api调用而不是在静态json中定义翻译来加载翻译?如何在React-i18next中做到这一点?

时间:2019-06-25 07:17:59

标签: reactjs i18next react-i18next

在React应用程序中使用国际化时,需要使用api调用按需加载语言翻译文件,而无需预先定义它们。如何通过使用React-i18next来实现?

尝试使用React-i18next从静态预定义文件中选取正常翻译。使用xhr-backend进行了尝试,但无法找到任何示例来实现按需加载翻译相关数据的要求。

2 个答案:

答案 0 :(得分:2)

import i18n from "i18next";
import LanguageDetector from "i18next-browser-languagedetector";
import backend from 'i18next-http-backend';
import axiosInstance from './helpers/Axios';

const loadResources=async(locale:string)=> {
    return await axiosInstance().get('/translate-data/get', { params: { lang: locale } })
      .then((response) => { return response.data })
      .catch((error) => { console.log(error); });
}

const backendOptions = {
  loadPath: '{{lng}}|{{ns}}', 
  request: (options:any, url:any, payload:any, callback:any) => {
    try {
      const [lng] = url.split('|');
      loadResources(lng).then((response) => {
        callback(null, {
          data: response,
          status: 200, 
        });
      });
    } catch (e) {
      console.error(e);
      callback(null, {
        status: 500,
      });
    }
  },
};

i18n
  .use(LanguageDetector)
  .use(backend)
  .init({
    backend: backendOptions,
    fallbackLng: "en",
    debug: false,
    load:"languageOnly",
    ns: ["translations"],
    defaultNS: "translations",
    keySeparator: false, 
    interpolation: {
      escapeValue: false, 
      formatSeparator: ","
    },
    react: {
      wait: true
    }
});

export default i18n;

来自后端选项的请求用于使用 Axios 调用后端 API。

答案 1 :(得分:0)

import i18next from 'i18next';

import XHR from 'i18next-xhr-backend';


var language = i18next.language ||'en-US';


const backendOptions = {
  type: 'backend',

  crossDomain: false,

  allowMultiLoading: false,

  loadPath: `your-backend-api/?locale_code=${language}`

}

const options = {

  interpolation: {

    escapeValue: false, // not needed for react!!

  },

  initImmediate: false ,


  debug: true,    


  lng: language,


  fallbackLng: language,


  // have a common namespace used around the full app

  ns: ['translations'],

  defaultNS: 'translations',


  react: {
    wait: false,

    bindI18n: 'languageChanged loaded',

    bindStore: 'added removed',

    nsMode: 'default',

    defaultTransParent: 'div',

  },
};



options['backend'] = backendOptions;

i18next
  .use(XHR)
  .init(options)


export default i18next;