[英]How to updaye i18next configuration?
我想在我的项目中使用 react-i18next,并且我想使用从服务器获取的数据来配置 i18 设置,所以它是一个异步 function。
我想到的第一个 senario 是使用这个:
useEffect(() => {
console.log("i18n_useEffect", i18n);
setTimeout(function() {
console.log(
"fetch data from server,and then reset i18n.js configuration"
);
const configurationFromServer = {...};
localStorage.setItem("i18n_configuration",configurationFromServer)
seti18nLoaded(true);
}, 3000);
},[]);
seti18nLoaded && <Componenrts/>
首先,我们从服务器获取配置数据,一旦完成,我们就可以在里面显示和使用 i18n。
但它看起来不正确,因为如果配置 api 失败或在我得到数据之前。 我想先给出一个默认设置,然后再更新它。
像这样:
import i18n from "i18next";
import LanguageDetector from "i18next-browser-languagedetector";
import { initReactI18next } from "react-i18next";
const init_i18n = configFromServer => {
i18n
.use(LanguageDetector)
.use(initReactI18next)
.init(configFromServer);
};
const defaultConfig = {
// we init with resources
resources: {},
fallbackLng: "en",
debug: true,
// have a common namespace used around the full app
ns: ["translations"],
defaultNS: "translations",
keySeparator: false, // we use content as keys
interpolation: {
escapeValue: false
}
};
const configFromServer = {
// we init with resources
resources: {
en: {
translations: {
Hello: "Hello",
welcome: "welcome",
"Use string as key": "Use string as key"
}
},
de: {
translations: {
"Use string as key": "Use string as key_de",
Hello: "Hello_de",
welcome: "welcome_de"
}
}
},
fallbackLng: "en",
debug: true,
// have a common namespace used around the full app
ns: ["translations"],
defaultNS: "translations",
keySeparator: false, // we use content as keys
interpolation: {
escapeValue: false
}
};
const initialize = () => {
i18n
.use(LanguageDetector)
.use(initReactI18next)
.init(defaultConfig);
setTimeout(() => {
console.log("fetch data from server");
//I want update the configuration here.but not work.
init_i18n(configFromServer);
}, 2000);
};
initialize();
export default i18n;
所以想法是我们使用默认配置初始化一次,然后根据我们从服务器拉取的数据更新它
我将使用以下方式,因为我希望它在从服务器加载或获取失败的 i18next 配置之前默认显示英文文本。
我不确定我的想法是否是正确的方法。 我还看了一下 i18next-xhr-backend,它看起来在 init function 中配置了 api 路径,但是很难理解,如果有人可以举一个使用 i18next-xhr 的示例,将会很有帮助- .
反正我这里有一个在线demo可以解释的更清楚: https://codesandbox.io/s/react-i18next-gpzyc
我有一个 fack api 来测试配置: https://my-json-server.typicode.com/jjzjx118/demo/db
它返回:
{
"en": {
"translations": {
"Hello": "Hello",
"welcome": "welcome",
"Use string as key": "Use string as key"
}
},
"de": {
"translations": {
"Use string as key": "Use string as key_de",
"Hello": "Hello_de",
"welcome": "welcome_de"
}
}
}
感谢您。
我已经检查了您的沙箱链接,并且i18n
实例已经从新配置中重新初始化。 您缺少的是手动选择您喜欢的语言。
由于您使用的是LanguageDetector
,它只会 select 基于浏览器的语言等。如果您想在从服务器获取请求后手动更改它,您可以在重新初始化后调用i18n.changeLanguage("de")
.
在你的情况下:
setTimeout(() => {
console.log("fetch data from server");
init_i18n(configFromServer);
// You can change the language here based on the config
i18n.changeLanguage("de");
}, 2000);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.