【发布时间】:2019-03-24 12:59:58
【问题描述】:
我有以下 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 脚本中进行哪些更改?谢谢。
【问题讨论】:
-
你不能只使用 fetch 吗?为什么需要 i18next-xhr-backend 和 axios?
-
以上是我的第一次尝试。我对它不是很熟悉。看来他们不会接受非json文件。
-
对不起,我对 i18next 也不是很熟悉。我想像:
fetch("XXX.php").then((res)=>(res.json())).then((data)=>{i18next.init({resources: data})},但那可能完全不对。
标签: reactjs i18next react-i18next