我想在使用i18next-fetch-backend
的客戶端上使用react-i18next
,即使我可以通過瀏覽器訪問JSON翻譯文件,在init
例行程序中處理。無法通過FETCH後端得到react-i18next來讀取JSON文件
爲了記錄,我使用create-react-app
作爲我的前端React應用程序的基礎,如果這樣做有所不同,並且到目前爲止我所有的測試都在本地主機上(使用localhost上的React應用程序:和localhost:8000上的「服務器」)。
這是我的init文件:
import i18n from 'i18next';
import LanguageDetector from 'i18next-browser-languagedetector';
import Cache from 'i18next-localstorage-cache';
import Fetch from 'i18next-fetch-backend';
i18n
.use(LanguageDetector)
.use(Cache)
.use(Fetch)
.init({
fallbackLng: 'en',
ns: ['common','app'],
defaultNS: 'common',
preload: ['en'],
wait: true,
backend: {
loadPath: 'http://localhost:8000/static/locales/{{lng}}/{{ns}}.json',
addPath: 'http://localhost:8000/static/locales/{{lng}}/{{ns}}',
parse: function (data) { console.log("DATA", data) },
init: {
mode: 'no-cors',
credentials: 'include',
cache: 'default'
}
},
cache: {
enabled: true,
prefix: 'i18next_translations_',
expirationTime: 24*60*60*1000 //one day
},
debug: true,
detection: {
order: ['localStorage', 'cookie'],
lookupCookie: 'i18nextLng',
lookupLocalStorage: 'i18nextLng',
caches: ["localStorage"]
//cookieMinutes: 10 // if we want the cookie to expire
},
});
export default i18n;
...然後組件,它包裝我的應用程序是這樣的:
import React, { Component } from 'react';
import { I18nextProvider } from 'react-i18next'
import i18n from './i18n' // the init code from above
export default class Localize extends Component {
render() {
return (
<I18nextProvider i18n={i18n}>
{this.props.children}
</I18nextProvider>
)
}
}
...最後,該組件在翻譯時應發生:
class TestTranslate extends Component {
render() {
const { t } = this.props;
return (
<div>
{t('key1')}
{t('key3')}
</div>
)
}
}
export default translate()(LearnHome)
執行兩個FETCH命令:一個用於,另一個用於app.json
。在我看來,它確實看起來好像兩個FETCH命令都能正確執行,但是根本沒有任何數據正在將它配置到backend
init配置數據中的parse()
函數中。
而事實上,如果我彈出了到Chrome網絡標籤,瀏覽器肯定似乎認爲該數據被正確地從服務器返回給瀏覽器:
所以我對發生了什麼事感到困惑。我已經通過i18next文檔和幾個例子,但迄今爲止空着。任何幫助表示讚賞。
謝謝!
這個問題本身是我找到的用於設置react-i18next的最佳資源。 – np8