简体   繁体   English

如何从React的promise中获取响应数据?

[英]How to get the response data from promise in React?

I am setting up a very basic react app, and trying to call my local host server (separate backend server), which has JSON data on it. 我正在设置一个非常基本的反应应用程序,并尝试调用我的本地主机服务器(单独的后端服务器),其上有JSON数据。 I want to extract the data returned from the promise, but nothing I do seems to work. 我想提取从promise返回的数据,但我做的任何事情似乎都没有用。 Here is my code: 这是我的代码:

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

I have tried response.json(), response.body, I tried logging the body with .then(functio(body) { console.log(body)}), response.data, response.body, but nothing works. 我尝试过response.json(),response.body,我尝试用.then(functio(body){console.log(body)}),response.data,response.body记录身体,但没有任何效果。 Here is what the console prints out: 以下是控制台打印出来的内容:

在此输入图像描述

How can I take the output it is giving me, and get it in an array that I can iterate through? 我如何获取它给我的输出,并将其放入我可以迭代的数组中? The "content" and "id" are what I need access to. “内容”和“id”是我需要访问的内容。

and FYI, the array, when i go to localhost:8080/posts in my browser is simple: 和FYI,阵列,当我去localhost:8080 /我的浏览器的帖子很简单:

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

any help is appreciated, thanks! 任何帮助表示赞赏,谢谢!

The call to response.json() will also return a promise so you need too handle that also. response.json()的调用也将返回一个promise,所以你也需要处理它。 Try the code below. 请尝试下面的代码。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM