【问题标题】:React-Native assign a JSON Object fetched from url to a variableReact-Native 将从 url 获取的 JSON 对象分配给变量
【发布时间】:2017-05-05 20:44:06
【问题描述】:

我在 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: undefined is not an object (evalating 'resp.primoanno[0]')”

如果我将 responseJson.lista 包装到 console.log 函数中,我会看到我的 JSON 字符串已格式化。但我不能将它分配给变量。请问你能帮帮我吗? 提前谢谢你

【问题讨论】:

    标签: javascript json variables react-native fetch


    【解决方案1】:

    正如@jaws 所指出的,您的函数getJsonData 返回一个promise,而不是responseJson.lista 的实际值。

    这是一个可运行的 sn-p,您可能会注意到我更改了 url,这是因为您的原始链接不是 https,并且 fetch 失败并出现以下错误:

    混合内容:页面位于 “……” 已通过 HTTPS 加载,但请求了不安全的资源 '……'。 此请求已被阻止;内容必须通过 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]);
    });

    【讨论】:

    • 感谢您的回答。我仍然有一个问题..当我获取整个 API 时,它不允许我将它作为 JSON 对象访问。如果我将整个数据放入先前创建的名为“data”的变量中,然后在获取链之后键入 console.log(data.primoanno[0]) 日志会显示“未定义不是对象”.. 即使我字符串化它并重新解析它我得到了同样的错误..访问某些数据的唯一方法是映射它..但我只需要整个对象作为Json..有什么办法让它工作吗?
    【解决方案2】:

    这里,getJsonData 返回一个承诺,所以你需要这样访问它。

    getJsonData().then((data) => { console.log(data.primoanno[0] }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-25
      • 2019-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-24
      相关资源
      最近更新 更多