【发布时间】:2020-12-20 02:34:59
【问题描述】:
我目前在网站的本地化过程中遇到了障碍。使用 i18next,我们所有的路由都会被翻译,并且默认语言会从 URL 中删除语言环境路径。
换句话说:
/accueil -> /en/home
/produits -> /en/products
等等……
我的问题是当我更改语言时,url 不跟随(这是可以预料的,因为 i18next 不直接与 react-router 对话)。
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,但是找到当前页面的键会增加很多复杂性。
提前感谢您提供的任何帮助。
【问题讨论】:
标签: react-router localization internationalization i18next react-i18next