想使用React js和i18next将Locale添加到路径中吗



我正在使用React Js和i18next来尝试构建一个具有多种语言的应用程序

我想在我的URL中生成本地,前缀会在URL中多次添加的问题!

这是我的配置:

i18n.js

i18n
// i18next-http-backend
// loads translations from your server
// https://github.com/i18next/i18next-http-backend
.use(Backend)
// detect user language
// learn more: https://github.com/i18next/i18next-browser-languageDetector
.use(LanguageDetector)
// pass the i18n instance to react-i18next.
.use(initReactI18next)
// init i18next
// for all options read: https://www.i18next.com/overview/configuration-options
.init({
debug: true,
supportedLngs: ['de','en','fr'],
fallbackLng: 'de',
whitelist: ['de','en','fr'],
detection: {
order: ['path','cookie', 'htmlTag', 'localStorage', 'sessionStorage','subdomain'],
caches: ['cookie'],
lookupFromPathIndex: 0,
checkWhitelist: true
},
interpolation: {
escapeValue: false, // not needed for react as it escapes by default
// format: (value, format, lng) => { // legacy usage
//   if (value instanceof Date) {
//     return DateTime.fromJSDate(value).setLocale(lng).toLocaleString(DateTime[format])
//   }
//   return value;
// }
},
backend: {
loadPath: '/locales/{{lng}}/translation.json',
}
});

路由:

function App() {
const baseRouteUrl = "/:locale(en|de|fr)?";
return (
//@todo add baseurl
<I18nextProvider i18n={i18next}>
<BrowserRouter >
<Suspense fallback={<p>...Loading</p>}>
<Switch>
<Route exact path={baseRouteUrl + "/"} component={Home} />
<Route path={baseRouteUrl + "/about"} component={About} />
</Switch>
</Suspense>
</BrowserRouter>
</I18nextProvider>
);
}

导航:

const Navigation = () => {
const baseUrl = cookies.get('i18next');
return (

<Link to={baseUrl + "/"}> Home </Link>
<br/>
<Link to={baseUrl + "/about/"}>About </Link>

);
};

URL应该是:

http://localhost:3000/en/about/

http://localhost:3000/en/de/about/

感谢您的帮助!

cookie的值是多少?

如果使用resolvedLanguage值,会有帮助吗?

<Link to={i18n.resolvedLanguage + "/about/"}>About </Link>

顺便说一句:你可以删除白名单选项,白名单被重命名为supportedLngs

最新更新