在过去的几天里,我一直在努力解决这个问题。我有一个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;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>
);这给了我以下控制台警告: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>
);这仍然没有解决问题,我确实得到了相同的控制台输出。
发布于 2022-05-26 12:09:38
我不知道应用程序的大小和URI模式的复杂性,但是在这里,我们已经将语言参数从URI更改为本地存储中的用户信息。
我们使用的是罗塞塔,使用起来非常简单,也很容易从用户信息或默认的.env properties文件中初始化。
https://stackoverflow.com/questions/72390842
复制相似问题