Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在React中从promise获取响应数据?_Javascript_Json_Reactjs - Fatal编程技术网

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

Javascript 如何在React中从promise获取响应数据?,javascript,json,reactjs,Javascript,Json,Reactjs,我正在设置一个非常基本的react应用程序,并尝试调用本地主机服务器(单独的后端服务器),其中包含JSON数据。我想提取从承诺中返回的数据,但我所做的一切似乎都不起作用。这是我的密码: fetch('http://localhost:8080/posts') .then(function(response) { const items = response.json() console.log(items) }) 我尝试过response

我正在设置一个非常基本的react应用程序,并尝试调用本地主机服务器(单独的后端服务器),其中包含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记录body,但没有任何效果。以下是控制台打印的内容:

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

仅供参考,当我在浏览器中转到localhost:8080/posts时,数组很简单:

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

感谢您的帮助,谢谢

调用
response.json()
也将返回一个承诺,因此您也需要处理它。请尝试下面的代码

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

控制台的代码是什么打印输出我输入的代码,const items=response.json()console.log(items),生成我输入image.response.data的打印输出“undefined”,那么,如果response.json()已经返回一个promise:fetch('api/SampleData/WeatherForecasts'),为什么我还可以发现这个代码段是可执行的呢.then(response=>response.json()作为Promise).then(data=>{this.setState({预测:数据,加载:false});});如何在外部访问此代码中的常量项?除了使用setState还有其他方法吗?我认为您可以在(无var声明)全局范围内访问它,但您应该问的问题是,除了调用“then”回调外,我如何确保它已设置。