【发布时间】:2021-06-14 13:44:06
【问题描述】:
我有以下问题:我使用 react 和 i18next 并且还使用 i18next-backend 加载我的翻译文件。我有一个 languageSwitcher,我不仅要使用它来更改语言,还要使用它来更改 URL。 但我需要在更改语言之前访问新语言的命名空间“路由”。 我该怎么做?
这是我的 i18n 配置:
i18n
.use(initReactI18next)
.use(detector)
.use(HttpApi)
.init({
defaultNS: 'routes',
fallbackLng: ['de'],
supportedLngs: ['de', 'en'],
detection: {
order: ['path'],
lookupFromPathIndex: 0,
},
backend: {
loadPath: '/locales/{{lng}}/{{ns}}.json',
},
keySeparator: false,
interpolation: {
format,
},
});
export default i18n;
我的语言选择器使用这个功能:
changeLanguage = (ln) => {
const routes = i18n.getResourceBundle(i18n.language, 'routes');
const currentPathname = window.location.pathname.replace(/\/+$/, '');
let currentRouteKey = Object.keys(routes).find((key) => routes[key] === currentPathname);
if (ln === 'en' && currentPathname === '') {
currentRouteKey = '/en';
}
window.location.replace(this.props.t('routes:' + currentRouteKey, { lng: ln }));
};
德语是我的后备语言,当我从应用程序的英文版本开始时,语言更改有效,但当我从德语版本开始时,它不起作用。我猜那是因为没有加载英文文件。如何触发此文件?
【问题讨论】:
标签: reactjs i18next react-i18next