【问题标题】:How to get the response data from promise in React?如何从 React 中的 Promise 中获取响应数据?
【发布时间】:2017-12-28 14:34:46
【问题描述】:

我正在设置一个非常基本的反应应用程序,并尝试调用我的本地主机服务器(单独的后端服务器),它上面有 JSON 数据。我想提取从承诺返回的数据,但我所做的一切似乎都不起作用。这是我的代码:

    fetch('http://localhost:8080/posts')
    .then(function(response) {
        const items = response.json()
        console.log(items)
    })

我尝试过 response.json()、response.body,我尝试使用 .then(functio(body) { console.log(body)})、response.data、response.body 记录正文,但没有任何效果.以下是控制台打印的内容:

如何获取它给我的输出,并将其放入我可以迭代的数组中? “内容”和“id”是我需要访问的。

当我在浏览器中访问 localhost:8080/posts 时,数组仅供参考:

  [{"id":1,"content":"hello, this is post 1"}]

感谢任何帮助,谢谢!

【问题讨论】:

  • 你的控制台打印出来的代码是什么
  • 我输入的代码 const items = response.json() console.log(items) 会产生我放入图像的打印输出。
  • response.data 打印“未定义”

标签: javascript json reactjs


【解决方案1】:

response.json()的调用也会返回一个promise,所以你也需要处理它。试试下面的代码。

fetch('http://localhost:8080/posts')
.then(function(response){ return response.json(); })
.then(function(data) {
    const items = data;
    console.log(items)
})

【讨论】:

  • 那么,如果 response.json() 已经返回了一个承诺,为什么我可以找到这段代码 sn-p 也可执行: fetch('api/SampleData/WeatherForecasts') .then(response => response .json() as Promise) .then(data => { this.setState({ Forecasts: data, loading: false }); });
  • 如何在外部访问这段代码中的 const 项?除了使用 setState 还有其他方法吗?
  • 我认为您可以在(无 var 声明)全局范围内访问它,但您应该问的问题是,除了调用“then”回调时,我如何确定它已设置。跨度>
猜你喜欢
  • 1970-01-01
  • 2017-09-19
  • 1970-01-01
  • 2021-06-14
  • 1970-01-01
  • 1970-01-01
  • 2021-11-12
  • 1970-01-01
  • 2023-03-18
相关资源
最近更新 更多