0

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

4

1 回答 1

1

诀窍是:

通过导入添加资源,您有一些结构,例如:

{ 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

于 2019-03-25T11:14:48.993 回答