6

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

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

4

2 回答 2

4
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。

于 2021-02-08T07:13:56.090 回答
3
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;
于 2019-11-25T13:02:34.307 回答