React Native fetch() returns 奇数 json 响应项

React Native fetch() returns odd json response items

我正在尝试从名为 OpenWeatherMap 的服务中获取 JSON 数据,因此在我的 componentWillMount 方法中,我通过 url 调用 fetch() 到 return 数据。我现在的代码是:

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

有效,但 JSON 响应中的 return 奇数数据,我现在的 JSON 响应是:

{"_40":0,"_65":1,"_55":{here_the_correct_response}}

但我希望我的响应没有这些奇怪的下划线索引,只是纯粹的 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 */);

我不知道为什么我应该 "promise decryption" 两次,但它有效。对此进行解释的任何评论表示赞赏。

更新

感谢,我现在理解正确了。

fetch() 函数没有返回承诺,正如我之前写的那样。它 returns 一个 Response 对象,其中包含有关 request/response 的信息(比如它的状态)和我们需要的 ReadableStream 格式的数据。

json() 函数反过来,returns 包含将 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()) 批准。您会看到类似的结果。

获取 return 响应对象包含一些信息,例如 request/response 状态。并且您感兴趣的数据由服务器 return 编辑在 Response.body.

此数据为ReadableStream格式。响应对象具有 json() 函数,这将 return 包含将可读流转换为 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 */);