[英]How to change URL path using react-i18next?
在過去的幾天里,我一直在為這個問題而苦苦掙扎。 我有一個 React 應用程序,我正在嘗試通過使用 i18next 使其成為多語言。 我想根據所選語言更改 url 路徑,例如 http://localhost:3000/en、http://localhost:3000/bg、http://localhost:3000/en/about 等。
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;
索引.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>
);
這給了我以下控制台警告: No routes matched location "/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>
);
這仍然不能解決問題,我得到了相同的控制台 output。
我不知道您的應用程序的大小和 URI 架構的復雜性,但在這里,我們已將語言參數從 URI 更改為本地存儲中的用戶信息。
我們正在使用Rosetta ,它使用起來非常簡單,而且很容易從用戶信息或默認.env properties
文件進行初始化。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.