简体   繁体   English

如何使用 react-i18next 更改 URL 路径?

[英]How to change URL path using react-i18next?

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.我有一个 React 应用程序,我正在尝试通过使用 i18next 使其成为多语言。 I want to change the url path according to the selected language, eg http://localhost:3000/en, http://localhost:3000/bg, http://localhost:3000/en/about etc.我想根据所选语言更改 url 路径,例如 http://localhost:3000/en、http://localhost:3000/bg、http://localhost:3000/en/about 等。

i18n.ts file: 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:索引.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.这给了我以下控制台警告: No routes matched location "/en/catalog"或我尝试的任何其他 url。

What am I missing?我错过了什么?

Edit: I've noticed that I have nested routing so the baseUrl should only be added to the parent route:编辑:我注意到我有嵌套路由,所以 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>
);

That still doesn't fix the issue and I do get the same console output.这仍然不能解决问题,我得到了相同的控制台 output。

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.我不知道您的应用程序的大小和 URI 架构的复杂性,但在这里,我们已将语言参数从 URI 更改为本地存储中的用户信息。

We're using Rosetta , that is incredibly simple to use and also very easy to initialize from user info or default .env properties file.我们正在使用Rosetta ,它使用起来非常简单,而且很容易从用户信息或默认.env properties文件进行初始化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM