我目前在网站的本地化过程中遇到了障碍。使用 i18next,我们的所有路由都会被翻译,并且默认语言已从 URL 中删除区域设置路径。
换句话说:
/accueil -> /en/home
/产品 -> /en/产品
等等...
我的问题是当我更改语言时,URL 不跟随(这是预料之中的,因为 i18next 不直接与反应路由器对话)。
i18下一个配置:
i18n
.use(detector)
.use(initReactI18next)
.init({
whitelist: ['fr', 'en'],
fallbackLng: 'fr',
defaultNS: 'common',
detection: {
lookupFromPathIndex: 0,
checkWhitelist: true
},
interpolation: {
escapeValue: false
},
resources: {
en: {
routes: enRoutes,
[...]
},
fr: {
routes: frRoutes,
[...]
}
}
});
fr/routes.json:
{
"home": "/accueil",
"products": "/produits",
[...]
}
en/routes.json:
{
"home": "/en/home",
"products": "en/products",
[...]
}
app.jsx 中的路由器部分:
<Router forceRefresh>
<Switch>
<Route path={`/:locale(en|fr)?${t('routes:home')}`} component={HomeComponent} />
<Route path={`/:locale(en|fr)?${t('routes:products')}`} component={ProductsComponent} />
</Switch>
</Router>
使用以下配置,页面呈现没有问题,并且在调用 i18n.changeLanguage 时可以轻松翻译,但 url 不会随之更改。我到处搜索过,但似乎找不到在语言更改后翻译网址的首选方法。
我还想处理用户直接在浏览器 URL 字段中手动更改区域设置的情况。
我尝试过更新 i18next 中“languageChanged”事件的 url,但找到当前页面的密钥会增加很多复杂性。
提前感谢您提供的任何帮助。
我终于找到了一种简单干净的方法来更改路线,同时也更改语言。
const changeLanguage = (nextLanguage) => {
const routes = i18n.getResourceBundle(i18n.language, 'routes');
const currentPathname = window.location.pathname.replace(/\/+$/, '');
const currentRouteKey = Object.keys(routes).find((key) => routes[key] === currentPathname);
window.location.replace(t(`routes:${currentRouteKey}`, { lng: nextLanguage }));
};
我还需要更改 i18next 检测选项,如下所示:
detection: {
order: ['path', ...otherMethods]
lookupFromPathIndex: 0,
checkWhitelist: true
},
我现在可以在任何地方安全地调用此changeLanguage包装器,它将处理语言更改(如果它不是网址的一部分,则变为默认值)和路由更改。