更改语言时翻译不会更改。我正在使用 MobX 来存储语言的状态。更改语言会更改 I18nContext.Provider 中的区域设置,但页面上的文本不会更改。
我的钩子(Hook)。
import {useI18n} from "@shopify/react-i18n";
import enTrans from "../../translate/en.json";
import frTrans from "../../translate/fr.json";
export const UseI18nHook = () => {
console.log('hook1');
return useI18n({
id: 'App',
fallback: 'fr',
translations(locale) {
return locale === "en" ? enTrans : frTrans;
},
})};
我的翻译提供商
import React from "react";
import {inject, observer} from "mobx-react";
import {I18nContext, I18nManager} from '@shopify/react-i18n';
const TranslateWrapper = inject(stores => ({
activeEnglish: stores.LocalizeStore.activeEnglish
}))(observer(({activeEnglish, children}) => {
return(
<I18nContext.Provider value={new I18nManager({
locale: activeEnglish ? 'en' : 'fr',
onError(error) {
console.log(error);
},
})}>
{children}
</I18nContext.Provider>
)
}));
export default TranslateWrapper;
在页面中我使用 const [i18n] = UseI18nHook();
和 i18n.translate('App.InstallPage.installTitle')
最佳答案
我的实现方式如下: 首先,我将使用自定义翻译 Hook 来处理我的所有逻辑
import * as translations from "./Translations";
import { useEffect } from "react";
export default function useTranslation() {
const [language, setLanguage] = useState("ar");
const [fallbackLanguage, setFallbackLanguage] = useState("en");
//this is optional if the language is rtl
useEffect(() => {
document.documentElement.dir = language === "ar" ? "rtl" : "ltr";
}, [language]);
const translate = (key) => {
const keys = key.split(".");
return (
getNestedTranslation(language, keys) ?? //return the value of the key in the selected language
getNestedTranslation(fallbackLanguage, keys) ?? //return the value of the key in fallback language if there is no translation found in the main langrage
key // return the key itself if there is no translation found in the fallback language
);
};
return {
language,
setLanguage,
fallbackLanguage,
setFallbackLanguage,
t: translate,
};
}
function getNestedTranslation(language, keys) {
return keys.reduce((obj, key) => {
return obj?.[key];
}, translations[language]);
}
然后有一个名为 Translations 的文件夹,其中包含 index.js
export * as en from "./en.json";
export * as ar from "./ar.json";
//any other languages
以及包含翻译的 JSON 文件
en.json:
"hello":"Welcome"
ar.json:
"hello": "مرحبا"
在页面中我使用 const {t} = useTranslation();和 t('你好')
你也可以有像这样的嵌套键
"months": [
"feb",
"jan",
"mar"
]
并像这样使用它:t("months.1")(将返回二月)
在将更改语言的组件中执行以下操作,它应该重新呈现:
cosnt {setLanguage}=useTranslation();
const handleLangChange=(lang)=>{
setLanguage(lang);
}
关于reactjs - @shopify/react-i18n 中更改语言时如何重新渲染页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69708890/