如何使用 i18next 的 onLanguageChange 侦听器更改语言后更改/替换窗口的位置区域设置?

发布于 2025-01-09 04:21:47 字数 449 浏览 1 评论 0原文

我目前正在使用 React-Router-Dom v6、i18next 以及 React-i18next。

我希望一旦在应用程序内的任何位置切换语言,位置/链接中的区域设置就会更改。所以我有这个侦听器来检查语言更改:

./i18n.js

i18n.on('languageChanged', (lng) => {
  const { location } = window;
  location.replace('/ar/', `/${lng}/`).replace('/en/', `/${lng}/`);
});

const baseRouteUrl = '/:locale/';

问题是,一旦我重新加载页面,我就会看到无限循环。很明显,上部位置更换是原因。

我将如何修改侦听器以确保语言更改时不会无限重新加载/重新渲染?

I am currently using React-Router-Dom v6, i18next along with React-i18next.

I want the locale in the location/link to change once the language is switched anywhere inside the app. So I have this listener to check for language change:

./i18n.js

i18n.on('languageChanged', (lng) => {
  const { location } = window;
  location.replace('/ar/', `/${lng}/`).replace('/en/', `/${lng}/`);
});

const baseRouteUrl = '/:locale/';

The thing is, once I reload the page I witness an infinite loop. It is obvious that the upper location replacement is the cause.

How would I modify the listener to ensure no infinite reload/rerender on language change?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

转角预定愛 2025-01-16 04:21:47

最终使用正则表达式来匹配语言区域设置并动态重新替换它们:

i18n.on('languageChanged', (lng) => {
  const { location } = window;
  console.log(location.pathname, 24242424);
  if (location.pathname.match(/\/ar\/|\/en\//) && !location.pathname.includes(`/${lng}`)) {
    const newUrl = location.pathname.replace(/\/ar\/|\/en\//, `/${lng}/`);
    location.replace(newUrl);
  }
});

Ended up using regex to match language locales and relpace them dynamically:

i18n.on('languageChanged', (lng) => {
  const { location } = window;
  console.log(location.pathname, 24242424);
  if (location.pathname.match(/\/ar\/|\/en\//) && !location.pathname.includes(`/${lng}`)) {
    const newUrl = location.pathname.replace(/\/ar\/|\/en\//, `/${lng}/`);
    location.replace(newUrl);
  }
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文