简体   繁体   English

React i18next - 从 API 获取语言首选项并根据获取的首选项初始化 i18n

[英]React i18next - Get language preference from API and initialize i18n based on fetched preference

I am using React i18next library to do language translations in my react app.我正在使用 React i18next 库在我的 react 应用程序中进行语言翻译。

I need to fetch the language preference from API (Say User settings api) and then i need to initialize i18n with the language i got from API.我需要从 API(说用户设置 api)获取语言首选项,然后我需要使用从 API 获得的语言初始化 i18n。

But my i18n.js file initializes first (obviously) before API call being served.但是我的 i18n.js 文件首先(显然)在 API 调用被服务之前初始化。 Not sure how to handle this.不知道如何处理。 I am using react hooks and all functional components.我正在使用反应钩子和所有功能组件。

Please find below my code and my index.js has the below file imported请在我的代码下面找到,我的 index.js 已导入以下文件

// i18n.js
import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import translationEN from "./locale/en/translation.json";
import translationES from "./locale/es/translation.json";

const resources = {
    es: {
        translation: translationES,
    },
    en: {
        translation: translationEN,
    },
};

i18n.use(initReactI18next).init({
    resources,
    fallbackLng: "es",

    keySeparator: false,

    interpolation: {
        escapeValue: false,
    },
});

export default i18n;

Thanks in advance提前致谢

获得用户的语言设置后,您可以通过以下方式更新语言

i18n.changeLanguage(lang)

You can fetch API from the server when init app and then use API addResourceBundle of i18n to add locale file to i18init您可以在初始化应用程序时从服务器获取 API,然后使用 i18n 的 API addResourceBundle将语言环境文件添加到 i18init

Ref: https://www.i18next.com/overview/api#addresourcebundle参考: https://www.i18next.com/overview/api#addresourcebundle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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