React-Native 将从 url 获取的 JSON 对象分配给变量
React-Native assign a JSON Object fetched from url to a variable
我在 react-native 上获取 JSON 数据时遇到问题,here 是我需要的 Json 数据,我写了这段代码:
function getJsonData(){
return fetch('http://discaricaabusivadibyte.altervista.org/IngBioSched/PROFS.json')
.then((res)=> res.json())
.then((responseJson) => { return responseJson.lista})
.catch(error => console.log(error));
}
var resp=getJsonData();
console.log("faischifo");
console.log(resp.primoanno[0]);
日志:“5173 10207 E ReactNativeJS:未定义不是对象(正在评估 'resp.primoanno[0]')”
如果我将 responseJson.lista 包装到 console.log 函数中,我会看到我的 JSON 字符串已格式化。但我不能将它分配给一个变量。请问你能帮帮我吗?
提前谢谢你
在这里,getJsonData returns 一个承诺,因此您需要这样访问它。
getJsonData().then((data) => { console.log(data.primoanno[0] }
正如@jaws 指出的那样,您的函数 getJsonData
returns 是一个承诺,而不是 responseJson.lista
的实际值。
这是一个可运行的片段,您可能会注意到我更改了 url
,那是因为您原来的 link 不是 https
,并且获取失败并出现以下错误:
Mixed Content: The page at
'...'
was loaded over HTTPS, but requested an insecure resource
'...'.
This request has been blocked; the content must be served over HTTPS.
function getJsonData() {
return fetch('https://gist.githubusercontent.com/mamodom/90a441ac8dababa7b68015a9b506fee5/raw/69e247f03b5732b359b7e258ecae47f8e078131a/foo.json')
.then(res => res.json())
.then(responseJson => responseJson.lista)
.catch(error => console.log("error", error));
}
getJsonData().then(data => {
console.log("faischifo");
console.log(data.primoanno[0]);
});
我在 react-native 上获取 JSON 数据时遇到问题,here 是我需要的 Json 数据,我写了这段代码:
function getJsonData(){
return fetch('http://discaricaabusivadibyte.altervista.org/IngBioSched/PROFS.json')
.then((res)=> res.json())
.then((responseJson) => { return responseJson.lista})
.catch(error => console.log(error));
}
var resp=getJsonData();
console.log("faischifo");
console.log(resp.primoanno[0]);
日志:“5173 10207 E ReactNativeJS:未定义不是对象(正在评估 'resp.primoanno[0]')”
如果我将 responseJson.lista 包装到 console.log 函数中,我会看到我的 JSON 字符串已格式化。但我不能将它分配给一个变量。请问你能帮帮我吗? 提前谢谢你
在这里,getJsonData returns 一个承诺,因此您需要这样访问它。
getJsonData().then((data) => { console.log(data.primoanno[0] }
正如@jaws 指出的那样,您的函数 getJsonData
returns 是一个承诺,而不是 responseJson.lista
的实际值。
这是一个可运行的片段,您可能会注意到我更改了 url
,那是因为您原来的 link 不是 https
,并且获取失败并出现以下错误:
Mixed Content: The page at '...' was loaded over HTTPS, but requested an insecure resource '...'. This request has been blocked; the content must be served over HTTPS.
function getJsonData() {
return fetch('https://gist.githubusercontent.com/mamodom/90a441ac8dababa7b68015a9b506fee5/raw/69e247f03b5732b359b7e258ecae47f8e078131a/foo.json')
.then(res => res.json())
.then(responseJson => responseJson.lista)
.catch(error => console.log("error", error));
}
getJsonData().then(data => {
console.log("faischifo");
console.log(data.primoanno[0]);
});