几乎我尝试了在Stackoverflow上找到的每一个解决方案,这些解决方案对我来说都不起作用。
我尝试在获取数据后翻译REST API内容。
下面是一些片段:
i18n.js:
import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import LanguageDetector from "i18next-browser-languagedetector";
import Backend from "i18next-http-backend";
import axios from "axios";
const loadResources = async (locale) => {
return await axios
.get("https://jsonplaceholder.typicode.com/posts", {
params: { lang: locale },
})
.then((res) => {
return res.data.slice(0, 3);
})
.catch((err) => {
console.log(err);
});
};
const detectorOptions = {
order: ["cookie", "localStorage", "navigator"],
lookupCookie: "locales",
lookupLocalStorage: "locales",
caches: ["localStorage", "cookie"],
excludeCacheFor: ["cimode"],
checkWhiteList: true,
};
const backendOptions = {
loadPath: "/locales/{{lng}}/{{ns}}.json", //used to pass language and namespace to custom XHR function
request: (options, url, payload, callback) => {
try {
const [lng] = url.split("|");
loadResources(lng).then((data) => {
callback(null, {
data: JSON.stringify(data),
status: 200, //status code is required by XHR plugin to determine success or failure
});
});
} catch (e) {
console.error(e);
callback(null, {
status: 500,
});
}
},
};
i18n
.use(Backend)
.use(LanguageDetector)
.use(initReactI18next)
.init({
debug: true,
fallbackLng: "en",
backend: {
loadPath: "/locales/{{lng}}/{{ns}}",
},
detection: detectorOptions,
whitelist: ["en", "zh", "jp", "fr"],
interpolation: {
escapeValue: false,
},
});
export default i18n;
字符串
Demo.js
import { useTranslation } from "react-i18next";
import axios from "axios";
import { useEffect, useState } from "react";
export default function Demo() {
const { t } = useTranslation();
const [data, setData] = useState([]);
useEffect(() => {
axios
.get("https://jsonplaceholder.typicode.com/posts")
.then((res) => {
setData(res.data.slice(0, 3));
})
.catch((err) => {
console.log(err);
});
}, [data]);
return (
<>
<section>
{data.map((i, index) => {
return (
<>
<div key={index}>
<h4>{i.title}</h4>
<p>{i.body}</p>
</div>
</>
);
})}
</section>
</>
)
型
我不知道如何使用Axios从REST API内容加载翻译。但我知道i18next-http-backend
用于加载翻译。
注意:我发现这三个链接对我没有帮助。
- how to load api response data as translation in React-i18next?
- How can we load translations using api calls instead of having them defined in static jsons? How can this be done in React-i18next?的
- How to properly load i18n resources in next-i18next from api endpoints?(这是next.js应用程序)
locales
位于我的公用文件夹public\locales\{lng}.json
另外,我发现这个github问题的链接是断开的:(
i18next-http-backend github issue的
从昨天开始我就找不到解决这个问题的方法。而且,这让我很困惑!
请帮帮我!
1条答案
按热度按时间0qx6xfy61#
字符串