[英]How to dynamically add language to URL in React using i18next?
I need to add language to url ie this is how the URL looks now http://localhost:3000/, http://localhost:3000/news, but it needs to be like this http://localhost:3000/en , http://localhost:3000/en/news。
同时,当有人向本网站发送链接时,必须从链接中获取语言。 这是我的代码。 语言工作,点击改变。
import i18n from 'i18next'
import HttpApi from 'i18next-http-backend'
import LanguageDetector from 'i18next-browser-languagedetector'
import { initReactI18next } from 'react-i18next'
i18n
.use(LanguageDetector)
.use(initReactI18next)
.use(HttpApi)
.init({
supportedLngs: ['ru', 'en', 'kk'],
fallbackLng: "en",
detection: {
order: ["cookie", "localStorage", "htmlTag", "path", "subdomain"],
caches: ["cookie"],
},
interpolation: {
escapeValue: false
}
});
export default i18n;
但是如何自动添加到 URL 呢? 有没有现成的解决方案?
可以借助 react-routerv5 中的useParams()
钩子从 URL 获取参数。
在定义 url 时,您需要添加如下param value
: <Route path="/:lang/news" component={News} />
其中:lang
是您将从 URL 收到的值。
假设有人进入yourapp.com/en/news
,这里的参数 lang 将加载值en
。 所以,现在要提取这个值,你可以使用import { useParams } from "react-router-dom";
然后在 function 组件内(因为钩子仅在功能组件内工作): const { lang } = useParams();
其中 lang 是您的参数。
在此之后,您可以使用i18n
根据收到的语言进行翻译。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.