如何在React Native中加载用于i18n翻译的静态语言环境json



如果API语言失败,我将尝试添加一个回退本地json。在我的react原生应用程序的i18n.js文件中,我添加了两个路径:一个从API获取,另一个获取本地JSON翻译。但我无法加载本地翻译,因为react本机不接受我放置翻译的公用文件夹。

这是i18n.js文件。

import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import Backend from 'i18next-chained-backend';
import { getLocales } from 'react-native-localize';
import Axios from "axios";
import { API_BASE_URL } from '../../config';
import HttpApi from 'i18next-http-backend';
i18n
.use(Backend)
.use(initReactI18next)
.init({
lng: getLocales()[0].languageCode,
fallbackLng: "en",
debug: true,
interpolation: {
escapeValue: false,
},
backend: {
backends: [
HttpApi,
HttpApi
],
backendOptions: [
{
loadPath: `${API_BASE_URL}/xyzzzzzzz/{{lng}}`,
parse: (data) => {
return data
},
request: (options, url, payload, callback) => {
Axios.post(url, {
domain: `${API_BASE_URL}`
})
.then((res) => {
callback(null, res);
})
.catch((err) => {
callback(err, null);
});
},
},
{
loadPath: '/locales/{{lng}}/translation.json'
}
]
},
});
export default i18n;

翻译在root/public/locates/en/translation.json

您的react原生应用程序中可能没有运行本地http服务器。。。因此您不能使用HttpApi后端进行本地翻译。

在这里,您可以找到一个本地缓存的示例:https://www.i18next.com/how-to/caching#react-具有异步存储的本机缓存

或者,您可以通过资源选项定义本地翻译:https://github.com/i18next/react-i18next/blob/master/example/react-native/App.js#L20https://www.i18next.com/how-to/add-or-load-translations#add-在init上如果您在本地只有部分翻译集,则可以尝试使用partialBundledLanguages选项:https://www.i18next.com/overview/configuration-options

最新更新