【问题标题】:React Native fetch() returns odd json response itemsReact Native fetch() 返回奇数的 json 响应项
【发布时间】:2018-03-14 06:37:53
【问题描述】:

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

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

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

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

但我希望我的响应没有这些奇怪的下划线索引,只是纯 JSON 响应

【问题讨论】:

  • “纯 JSON 响应”是什么意思?
  • @guest271314 没有这些奇怪的下划线索引
  • 这似乎是响应。您可以解析响应并调整对象的属性或创建具有调整属性名称的新对象。

标签: javascript json fetch react-native-android


【解决方案1】:

好的,我自己想出来的。这个奇怪的数据被称为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 */);

我不知道为什么我应该做两次“承诺解密”,但它确实有效。感谢任何解释这一点的 cmets。

更新

感谢vdj4y's answer我现在理解正确了。

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

json() 函数反过来返回一个包含将ReadableStream 转换为纯js对象的结果的promise。为了操作promise返回的数据,需要then()函数。

这里更正了代码:

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

【讨论】:

  • 第二个“then”不做任何事情。需要第一个 then,因为您收到的数据在 ReadableStream 上。尝试 console.log(response)。你会得到你的请求的详细信息,当你想跟踪网络状态或类似的东西时,这可能会很方便。 response.json(),将 readableStream 转换为 json 数据。函数 json() 返回承诺。
  • @vdj4y 你的意思是then(data) aftet json() 完全没有必要吗?
  • 是的,只是 .then(response => response.json()).then(result => {/** 做点什么 */})
【解决方案2】:

Fetch 返回一个 Response 对象,其中包含一些信息,例如请求/响应状态。并且服务器返回的您感兴趣的数据在 Response.body 上。

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

【讨论】:

  • 感谢解释,不胜感激
【解决方案3】:

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

【讨论】:

    猜你喜欢
    • 2016-11-08
    • 2021-11-04
    • 2018-03-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-12
    • 2023-03-18
    • 1970-01-01
    • 2017-09-13
    相关资源
    最近更新 更多