我有以下PHP脚本来加载i18next转换的资源
<?php
$sql = 'SELECT * FROM translations';
...
header('Content-Type: application/json');
echo json_encode($translations);
?>
但是我如何在我的react js应用程序中使用它?最初,我在json中加载了客户端的翻译,就像在i18next官方教程中所做的那样。
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import translations from './translations.json';
const resources = translations;
i18n.use(initReactI18next).init({ resources, lng: 'zh', keySeparator: false, interpolation: { escapeValue: false } });
我想在服务器端使用PHP加载。但以下方法不起作用:
import i18n from 'i18next';
import xhr from 'i18next-xhr-backend';
import { initReactI18next } from 'react-i18next';
import axios from 'axios';
function loadCurrent(url, options, callback, data) {
axios.get(url).then((res) => {
callback(res.data, { status: res.status });
});
}
const i18nextOpt = {
backend: {
loadPath: 'http://localhost/translation.php',
parse: function(data) { return JSON.parse(data); },
ajax: loadCurrent
},
getAsync: false
};
i18n.use(xhr).init(i18nextOpt);
我的React脚本应该更改什么?谢谢。
诀窍是:
使用import添加资源你有一些结构,如:
{ lng: { ns: { key: value } } }
在xhr上,每个lng命名空间对都是单独加载的...所以文件必须是
{ key: value }
但是在lng / ns中请求 - >因此loadpath类似于:
http://localhost/{{lng}}/{{ns}}.php
https://www.i18next.com/how-to/add-or-load-translations
不需要axios就可以使用xhr-backend