react-native fetch 中的“then(res => res.json())”是什么意思? [重复]

问题描述 投票:0回答:3

react-native fetch 下面的代码片段中的

then(res => res.json())
是什么意思?

fetch(url)
      .then(res => res.json())
      .then(res => {
        this.setState({
          data: res,
          error: res.error || null,
          loading: false
        });
javascript react-native jsx fetch-api
3个回答
11
投票

这并不是一个真正的反应问题,因为 fetch 和 then 是 js 本身的一部分。

fetch 返回一个 Promise 对象,其中包含各种信息,如标头、HTTP 状态等。

你有

res.json()
和各种其他可能性。
.json()
将仅返回带有 json 内容的承诺正文。

了解更多信息:https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

您可以按如下方式返回数据:

  • .arrayBuffer()
  • .blob()
  • .json()
  • .text()
  • .formData()

6
投票

您的代码部分:

res => res.json()

是一个ES6箭头函数,翻译为:

function(res) {
    return res.json();
}

还有,关于

json()
功能:

Body mixin 的

json()
方法采用响应流并 读完它。它返回一个承诺,解决与 将正文文本解析为 JSON 的结果。

阅读更多这里


3
投票

Javascript

fetch
函数从指定的
url
异步提取资源。同时
fetch
返回
Promise
Promise
有助于异步部分,并在以获取的资源作为参数加载资源后运行传递到
then
(
res => res.json()
) 的函数。如果获取的资源是 JSON 格式,则可以使用
json()
来解析。

then
还返回
Promise
使其可链接。

fetch(url) // asynchronously load contents of the url
           // return a Promise that resolves when res is loaded
      .then(res => res.json()) // call this function when res is loaded
      // return a Promise with result of above function
      .then(res => { // call this function when the above chained Promise resolves
        this.setState({
          data: res,
          error: res.error || null,
          loading: false
        });

res => res.json()
也可以写成(但不完全等于)

function(res) { return res.json()}
© www.soinside.com 2019 - 2024. All rights reserved.