i18next后端loadPath无法映射数据
我正在尝试使用 i18next、react-i18next 和 axios 从第三方加载翻译。 这是我的 i18n.js:
import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import LanguageDetector from "i18next-browser-languagedetector";
import { DateTime } from "luxon";
import Backend from "i18next-http-backend";
import axios from "axios";
i18n
.use(Backend)
.use(LanguageDetector)
.use(initReactI18next)
.init({
debug: true,
fallbackLng: "en",
interpolation: {
escapeValue: false, // not needed for react as it escapes by default
format: (value, format, lng) => {
if (value instanceof Date) {
return DateTime.fromJSDate(value)
.setLocale(lng)
.toLocaleString(DateTime[format]);
}
return value;
},
},
backend: {
loadPath: (lng) => {
axios.get(`http://localhost:5000/${lng}`).then((res) => {
console.log(JSON.stringify(res.data));
return JSON.stringify(res.data);
});
},
},
});
export default i18n;
我可以在控制台上看到数据即将到来,但 useTranslation() 无论如何都不起作用。知道为什么会这样吗?
i'm trying to load the translation from the third party using i18next, react-i18next and axios.
Here is mine i18n.js:
import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import LanguageDetector from "i18next-browser-languagedetector";
import { DateTime } from "luxon";
import Backend from "i18next-http-backend";
import axios from "axios";
i18n
.use(Backend)
.use(LanguageDetector)
.use(initReactI18next)
.init({
debug: true,
fallbackLng: "en",
interpolation: {
escapeValue: false, // not needed for react as it escapes by default
format: (value, format, lng) => {
if (value instanceof Date) {
return DateTime.fromJSDate(value)
.setLocale(lng)
.toLocaleString(DateTime[format]);
}
return value;
},
},
backend: {
loadPath: (lng) => {
axios.get(`http://localhost:5000/${lng}`).then((res) => {
console.log(JSON.stringify(res.data));
return JSON.stringify(res.data);
});
},
},
});
export default i18n;
I can see on console that data is coming, but useTranslation() doesn't work anyway. Any idea why it's happening?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
loadPath 函数只是获取要加载的路径,而不是实际的加载请求。
为此,请使用请求选项:

https://github.com/i18next/i18next-http-backend#backend-options
尝试这样的操作:
在这里您还可以找到针对请求选项的专用测试:https://github.com/i18next/i18next-http-backend/blob/master/test/http.spec.js#L178
The loadPath function is just there to get the path to load, not the actual load request.
To do so use the request option:

https://github.com/i18next/i18next-http-backend#backend-options
Try something like this:
Here you can also find a dedicated test for the request option: https://github.com/i18next/i18next-http-backend/blob/master/test/http.spec.js#L178