如何解决更改语言时如何翻译位置网址?
在网站的本地化过程中,我目前正面临一堵墙。使用i18next,我们的所有路由都被翻译了,默认语言的语言环境路径已从URL中删除。
换句话说:
/ accueil-> / en / home
/产品-> / zh /产品
等等...
我的问题是,当我更改语言时,URL不跟随(这是可以预期的,因为i18next不会直接与react-router对话)。
i18next配置:
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包装器,它将处理语言更改(如果它不是url的一部分,则使用默认值)和路由更改。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。