Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.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 Native fetch()返回奇数json响应项_Javascript_Json_Fetch_React Native Android - Fatal编程技术网

Javascript React Native fetch()返回奇数json响应项

Javascript React Native fetch()返回奇数json响应项,javascript,json,fetch,react-native-android,Javascript,Json,Fetch,React Native Android,我试图从名为OpenWeatherMap的服务中以JSON的形式获取数据,所以在我的componentWillMount方法中,我调用fetch()以通过url返回数据。我现在的代码是: this.weather=fetch(url).then(response=>response.json()).then(responseJson=>responseJson); 它可以工作,但在JSON响应中返回奇数数据,目前我的JSON响应是: 但是我希望我的响应没有这些奇怪的下划线索引,只有纯JSON

我试图从名为OpenWeatherMap的服务中以JSON的形式获取数据,所以在我的componentWillMount方法中,我调用fetch()以通过url返回数据。我现在的代码是:

this.weather=fetch(url).then(response=>response.json()).then(responseJson=>responseJson);

它可以工作,但在JSON响应中返回奇数数据,目前我的JSON响应是:


但是我希望我的响应没有这些奇怪的下划线索引,只有纯JSON响应好的,我自己解决了。这种奇数数据称为
fetch()
返回的承诺。为了解决这个问题,我这样做了:

fetch(url)
    .then(response => response.json().then(data => data))
    .then(result => /* Do whatever you want with this result */)
    .catch(error => /* Do something if error occurs */);
我不知道为什么我应该做两次“承诺解密”,但它是有效的。任何解释这一点的评论都将不胜感激

更新 多亏了你,我现在理解正确了

fetch()。它返回一个
Response
对象,该对象包含有关请求/响应(如其状态)的信息以及我们需要的
ReadableStream
格式的数据

json()
函数依次返回一个承诺,该承诺包含将
ReadableStream
转换为普通js对象的结果。为了操作promise返回的数据,需要使用
then()
函数

更正代码如下:

fetch(url)
    .then(response => response.json())
    .then(result => /* Do whatever you want with this result */)
    .catch(error => /* Do something if error occurs */);

这种行为是正确的,因为
response.json()
实际上是一种承诺。
使用
console.warn(new Promise.resolve())
进行批准。您将看到类似的结果。

获取并返回一个响应对象,该对象包含一些信息,如请求/响应状态。服务器返回的您感兴趣的数据位于Response.body上

此数据为ReadableStream格式。响应对象具有json()函数,这将返回一个承诺,其中包含将readablestream转换为js对象的结果

如果您的服务器发送无效的json。运行response.json()时会发生错误,但不会在之前发生

fetch(url)
  .then(response => {
     console.log(response) // this contains some useful information about the reponse
     return response.json(); // convert readable stream to js object, if json is invalid, you will get the error here
  })
  .then(result => /* Do whatever you want with this result */)
  .catch(error => /* Do something if error occurs */);

你所说的“纯JSON响应”是什么意思?@guest271314没有这些看似响应的奇怪下划线索引。您可以解析响应并调整对象的属性,或者使用调整后的属性名称创建新对象。第二个“then”不起任何作用。然后需要第一个,因为您收到的数据是在ReadableStream上的。尝试console.log(响应)。您可以获得请求的详细信息,当您想要跟踪网络状态或类似情况时,这可能很方便。json(),将readableStream转换为json数据。函数json()返回promise@vdj4y你是说
then(data)
aftet
json()
根本就没有必要吗?是的,只是.then(response=>response.json())。然后(result=>{/**Do something*/})谢谢你的解释,非常感谢