[英]React JSON not returning object data
在我的 React App 中,我對組件內的文本字符串使用 JSON:
例子:
<h2>
{i18next.t('PODMODAL.title')}{' '}
</h2>
我從我的 JSON 文件收到此數據:
配置.JSON:
[
"PODMODAL": {
"title": "some info",
"firstline": "some info",
"secondline": "some info",
"cta: "click here"
}
]
當我運行 React App 時,它不會顯示字符串,而是顯示鍵而不是鍵的值。 例如在按鈕上。 它將顯示[PODMODAL.cta]
而不是[ CLICK HERE ]
[PODMODAL.cta]
獲取JSON.js
在這個文件中,我調用函數來字符串化我的 JSON:
function loadJSON(filePath) {
const json = loadTextFileAjaxSync(filePath, 'application/json');
return JSON.stringify(json);
}
function loadTextFileAjaxSync(filePath, mimeType) {
const xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', filePath, false);
if (mimeType != null) {
if (xmlhttp.overrideMimeType) {
xmlhttp.overrideMimeType(mimeType);
}
}
xmlhttp.send();
if (xmlhttp.status === 200) {
return xmlhttp.responseText;
} else {
return null;
}
}
window.userLang = navigator.language || navigator.userLanguage;
let language = window.userLang.split('-')[0];
export const data = loadJSON(
'../../../../locales/' + language + '/translation.json'
);
export const config = loadJSON('../../public/config/config.json');
我在控制台中沒有收到任何錯誤,但它沒有在屏幕上顯示正確的信息。 我不確定我做錯了什么,任何幫助將不勝感激。
更新我更新了問題以包含在 getJSON.js 中導出的兩個 JSON 文件(見上文)在控制台中查看,所有鍵上都存在以下錯誤:
i18next::translator: missingKey en-US translation GENERAL.join GENERAL.join
i18n.js :
import i18next from 'i18next';
import XHR from 'i18next-xhr-backend';
import { data, config } from './loadJSON';
i18next.use(XHR).init(
{
lng: window.userLang,
fallbackLng: window.userLang,
debug: true,
resources: {
it: {
translation: data,
config: config,
},
en: {
translation: data,
config: config,
},
},
},
function (err, t) {
// init set content
const language =
(navigator.languages && navigator.languages[0]) ||
navigator.language ||
navigator.userLanguage;
console.log('language ', language);
}
);
export default i18next;
這里有一些誤解
1- XMLHttpRequest 本質上是異步的,因此 loadJSON 函數將返回一個承諾,並且導出的配置不會立即准備好使用
2-您正在嘗試將 http 請求的結果字符串化,該結果已經是一個 json 文本,在這種情況下,您似乎需要 JSON.parse()
3- 您正在嘗試在編譯時加載一個無法正常工作的本地文件,因此您必須使您的翻譯可以通過網絡訪問,然后您可以使用 AJAX 請求 (xmlHttpRequest) 訪問它們,或者您可以在編譯類型 - 您必須配置構建工具鏈才能導入 json 文件
4- 總是最好使用已經建立的解決方案來解決既定的問題,內化是這些問題之一,尋找一個反應國際化的問題,這將是更好的選擇,然后嘗試重新發明一個新的
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.