![](/img/trans.png)
[英]React app keeps refreshing when changing i18next language in combination with authenticated routes
[英]How to add routes in a React/Gatsby app when I use i18next to handle translation?
所以最近我在我的 Gatsby 应用程序中实现了一个国际化功能,但它应该类似于一个 React 应用程序,所以如果你知道 React,请也告诉我你的经验,谢谢!
为了启用翻译功能,我使用react-i18next
。 我的文件结构如下所示:
-src
-locale
-en
-translation.js
-zh
-translation.js
-pages
-index.js
-......js
那么是怎么回事呢,我把pages
文件夹中文件的所有文本都提取出来放到translation.js
在不同的语言文件夹中,当我点击一个按钮改变语言时, pages
所有文件都会找到对应的相应地来自不同语言的translation.js
文件中的文本。
但路线根本没有改变。 有没有办法让我能够做到这一点:当我更改语言时,我的路线将从/en/index
更改为/zh/index
?
我知道我可以制作不同的页面,但我不想那样做,我想保持当前的处理方式以将我的文本与应用程序分开。 有没有我可以使用的包,或者你用什么来处理这个问题? 谢谢!
改变语言本身不会改变路线。 您将需要使用 gatsby 路由器来执行此操作(通过: await navigate('/:lang/path/slug')
)。 就像@jMadelaine 所说的那样,您不需要更改路由,因为它支持单个页面组件中的多语言 url 路由。
但是,如果您愿意,可以执行以下操作:
您可以使用i18next-browser-languagedetector
插件,并且需要在detection.order
数组中包含path
或querystring
,以便在 i18next 配置中初始化以进行语言检测。 https://github.com/i18next/i18next-browser-languageDetector#detector-options
然后在初始化 i18next 客户端时,您可以使用语言检测器,例如:
import i18next from "i18next"
import LanguageDetector from "i18next-browser-languagedetector"
const detection = {
// order and from where user language should be detected
order: [
"querystring",
"cookie",
"localStorage",
"navigator",
"htmlTag",
"path",
"subdomain",
],
// keys or params to lookup language from
lookupQuerystring: "lng",
lookupCookie: "i18next",
lookupLocalStorage: "i18nextLng",
lookupFromPathIndex: 0,
lookupFromSubdomainIndex: 0,
...
}
i18next.use(LanguageDetector).init({
detection, // <-- passed in here
whitelist: ["en", "es"],
fallbackLng: "en",
resources: i18nResources,
ns: ["translations"],
defaultNS: "translations",
returnObjects: true,
debug: process.env.NODE_ENV === "development",
react: { wait: true },
keySeparator: false,
supportedLngs: ["en", "es"],
lowerCaseLng: true,
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.