如何使用React-I18Next更改URL路径?

发布于 2025-02-01 12:25:49 字数 3046 浏览 2 评论 0原文

在过去的几天里,我一直在为这个问题而苦苦挣扎。我有一个React应用程序,我正在尝试通过使用I18Next来使其多语言。我想根据选定的语言更改URL路径,例如http:// localhost:3000/en,http:// localhost:3000/bg,http:// http:// localhost:3000/en/nod/over of等

。i18n.ts文件:

import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';

import Backend from 'i18next-http-backend';
import LanguageDetector from 'i18next-browser-languagedetector';
import i18next from 'i18next';

i18next.on('languageChanged', (lng) => { document.documentElement.setAttribute('lang', lng); })

i18n
    .use(Backend)
    .use(LanguageDetector)
    .use(initReactI18next)
    .init({
        supportedLngs: ['bg', 'en'],
        detection: {
            order: ['path', 'cookie', 'localStorage', 'sessionStorage', 'navigator', 'htmlTag'],
            caches: ['cookie'],
            lookupFromPathIndex: 0,
        },
        fallbackLng: 'bg',

        backend: {
            loadPath: '/locales/{{ns}}/{{lng}}.json'
        },
        ns: ['common', 'home']
    });

export default i18n;

index.tsx:

const baseUrl = "/:locale(bg|en)?";

const root = ReactDOM.createRoot(
  document.getElementById('root') as HTMLElement
);
root.render(
  <React.StrictMode>
    <CustomRouter history={customHistory}>
      <Suspense fallback='loading'>
        <Routes>
          <Route path={baseUrl + "/"} element={<App />}>
            <Route index element={<Home />} />
            <Route path={baseUrl + "catalog"} element={<Catalog />} />
            <Route path={baseUrl + "catalog/:id"} element={<ProductDetails />} />
            <Route path={baseUrl + "about"} element={<About />} />
            <Route path={baseUrl + "server-error"} element={<ServerError />} />
            <Route path="*" element={<NotFound />} />
          </Route>
        </Routes>
      </Suspense>
    </CustomRouter>
  </React.StrictMode>
);

这给了我以下控制台警告: 没有匹配的路由位置“/en/catalog”或我尝试的任何其他URL。

我想念什么?

编辑:我注意到我已经嵌套了路由,因此仅应将baseurl添加到父路由中:

const baseUrl = "/:locale(bg|en)?";

const root = ReactDOM.createRoot(
  document.getElementById('root') as HTMLElement
);
root.render(
  <React.StrictMode>
    <CustomRouter history={customHistory}>
      <Routes>
        <Route path={`${baseUrl}/`} element={<App />}>
          <Route index element={<Home />} />
          <Route path={"catalog"} element={<Catalog />} />
          <Route path={"catalog/:id"} element={<ProductDetails />} />
          <Route path={"about"} element={<About />} />
          <Route path={"server-error"} element={<ServerError />} />
          <Route path="*" element={<NotFound />} />
        </Route>
      </Routes>
    </CustomRouter>
  </React.StrictMode>
);

仍然无法解决问题,并且我确实获得了相同的控制台输出。

I've been struggling with this issue for the past couple of days. I have a React app and I am trying to make it multilingual by using i18next. I want to change the url path according to the selected language, e.g. http://localhost:3000/en, http://localhost:3000/bg, http://localhost:3000/en/about etc.

i18n.ts file:

import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';

import Backend from 'i18next-http-backend';
import LanguageDetector from 'i18next-browser-languagedetector';
import i18next from 'i18next';

i18next.on('languageChanged', (lng) => { document.documentElement.setAttribute('lang', lng); })

i18n
    .use(Backend)
    .use(LanguageDetector)
    .use(initReactI18next)
    .init({
        supportedLngs: ['bg', 'en'],
        detection: {
            order: ['path', 'cookie', 'localStorage', 'sessionStorage', 'navigator', 'htmlTag'],
            caches: ['cookie'],
            lookupFromPathIndex: 0,
        },
        fallbackLng: 'bg',

        backend: {
            loadPath: '/locales/{{ns}}/{{lng}}.json'
        },
        ns: ['common', 'home']
    });

export default i18n;

index.tsx:

const baseUrl = "/:locale(bg|en)?";

const root = ReactDOM.createRoot(
  document.getElementById('root') as HTMLElement
);
root.render(
  <React.StrictMode>
    <CustomRouter history={customHistory}>
      <Suspense fallback='loading'>
        <Routes>
          <Route path={baseUrl + "/"} element={<App />}>
            <Route index element={<Home />} />
            <Route path={baseUrl + "catalog"} element={<Catalog />} />
            <Route path={baseUrl + "catalog/:id"} element={<ProductDetails />} />
            <Route path={baseUrl + "about"} element={<About />} />
            <Route path={baseUrl + "server-error"} element={<ServerError />} />
            <Route path="*" element={<NotFound />} />
          </Route>
        </Routes>
      </Suspense>
    </CustomRouter>
  </React.StrictMode>
);

This gives me the following console warning:
No routes matched location "/en/catalog" or any other url that I try.

What am I missing?

Edit: I've noticed that I have nested routing so the baseUrl should only be added to the parent route:

const baseUrl = "/:locale(bg|en)?";

const root = ReactDOM.createRoot(
  document.getElementById('root') as HTMLElement
);
root.render(
  <React.StrictMode>
    <CustomRouter history={customHistory}>
      <Routes>
        <Route path={`${baseUrl}/`} element={<App />}>
          <Route index element={<Home />} />
          <Route path={"catalog"} element={<Catalog />} />
          <Route path={"catalog/:id"} element={<ProductDetails />} />
          <Route path={"about"} element={<About />} />
          <Route path={"server-error"} element={<ServerError />} />
          <Route path="*" element={<NotFound />} />
        </Route>
      </Routes>
    </CustomRouter>
  </React.StrictMode>
);

That still doesn't fix the issue and I do get the same console output.

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

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

发布评论

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

评论(1

小伙你站住 2025-02-08 12:25:49

我不知道您的应用程序的大小和您的URI模式的复杂性,但是在这里,我们已将语言参数从uri更改为本地商店中的用户信息。

我们正在使用 rosetta ,这非常易于使用,并且也很容易从用户信息或用户信息中初始化。默认.env属性文件。

I don't know about the size of your application and complexity of your URI schema, but here, we have changed the language parameter from URI to user info in local store.

We're using Rosetta, that is incredibly simple to use and also very easy to initialize from user info or default .env properties file.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文