我有以下 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 脚本中更改什么?谢谢你。