我正在尝试从名为 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 响应
最佳答案
好吧,我自己想通了。这个奇怪的数据就是所谓的 fetch()
返回的 promise 。为了摆脱这个我这样做了:
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 解密”,但它有效。任何对此进行解释的评论都将受到赞赏。
更新
感谢vdj4y's answer我现在理解正确了。
fetch()
函数没有返回 promise ,正如我之前写的那样。它返回一个 Response
对象,其中包含有关请求/响应的信息(如其状态)和我们需要的 ReadableStream
格式的数据。
json()
函数反过来返回一个 promise ,其中包含将 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 */);
关于javascript - React Native fetch() 返回奇怪的 json 响应项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46538248/