我对库i18next有问题。是的,此代码有效; //(我添加此文本是因为脚本未添加我的代码。愚蠢的文本看起来您的帖子大部分是代码;请添加更多详细信息。 看起来您的帖子大部分是代码;请添加更多详细信息 看起来您的帖子大部分是代码;请添加更多详细信息 看起来您的帖子大部分是代码;请添加更多详细信息)
文件:i18next
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import CustomBackend from './CustomBackend';
import LanguageDetector from 'i18next-browser-languagedetector';
const token = `${process.env.REACT_APP_API_TOKEN_POEDITOR}`;
const id = `${process.env.REACT_APP_API_ID_POEDITOR}`;
i18n
.use(CustomBackend)
.use(LanguageDetector)
.use(initReactI18next)
.init({
defaultLanguage: 'en',
otherLanguages: ['pl'],
fallbackLng: 'en',
debug: true,
saveMissing: true,
backend: {
// cors-anywhere is a trick. Don't use it in production
loadPath:
'https://cors-anywhere.herokuapp.com/https://api.poeditor.com/v2/terms/list',
addPath:
'https://cors-anywhere.herokuapp.com/https://api.poeditor.com/v2/terms/add',
crossDomain: true,
parse: (data) => {
const parsedData = JSON.parse(data);
const terms = parsedData.result.terms.reduce((acc, item) => {
acc[item.term] = item.translation.content || item.term;
return acc;
}, {});
return terms;
},
parsePayload: (namespace, key) => {
if (key === '_t') return;
const data = [
{
term: key,
},
];
const payload = {
api_token: token,
data: JSON.stringify(data),
id,
};
return payload;
},
parseLoadPayload: ({ lng }) => {
const payload = {
api_token: token,
language: lng,
id,
};
return payload;
},
},
interpolation: {
escapeValue: false, // not needed for react as it escapes by default
},
});
export default i18n;
文件CustomBackend:
import Backend from 'i18next-xhr-backend';
class CustomBackend extends Backend {
constructor(services, options = {}) {
super(services, options);
}
read(language, namespace, callback) {
var loadPath = this.options.loadPath;
const payload = this.options.parseLoadPayload({
lng: language,
ns: namespace,
});
if (typeof this.options.loadPath === 'function') {
loadPath = this.options.loadPath([language], [namespace]);
}
let url = this.services.interpolator.interpolate(loadPath, {
lng: language,
ns: namespace,
});
this.loadUrl(url, callback, payload);
}
loadUrl(url, callback, payload) {
this.options.ajax(
url,
this.options,
(data, xhr) => {
if (xhr.status >= 500 && xhr.status < 600)
return callback('failed loading ' + url, true /* retry */);
if (xhr.status >= 400 && xhr.status < 500)
return callback('failed loading ' + url, false /* no retry */);
let ret, err;
try {
ret = this.options.parse(data, url);
} catch (e) {
err = 'failed parsing ' + url + ' to json';
}
if (err) return callback(err, false);
callback(null, ret);
},
payload,
);
}
}
export default CustomBackend;