【问题标题】:What does 'then(res => res.json())' in react-native fetch mean? [duplicate]react-native fetch 中的 'then(res => res.json())' 是什么意思? [复制]
【发布时间】:2018-03-16 17:07:06
【问题描述】:

react-native fetch 下面sn-p中then(res => res.json())是什么意思?

fetch(url)
      .then(res => res.json())
      .then(res => {
        this.setState({
          data: res,
          error: res.error || null,
          loading: false
        });

【问题讨论】:

  • 如何更新?它没有表现出任何努力。 OP 甚至不知道 => 是什么。这可以通过查看 SO 和文档来简单地解决

标签: javascript react-native jsx fetch-api


【解决方案1】:

这并不是一个真正的反应问题,因为 fetch 然后是 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()

【讨论】:

  • 很好,但是resres.json() @GottZ 之间有=> 符号是什么意思
  • 这就是所谓的 lambda。那也是javascript的一部分。去这里了解更多信息:developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
  • @AniketSingh 基本上就是.then(function(res){return res.json()})
  • 但现在不要大肆宣传 lambda。 this 在 lambda 中会有所不同,并将引用周围的范围。
  • Move over people ;) 我认为这是重要的部分:请注意,尽管方法被命名为 json(),但结果不是 JSON,而是将 JSON 作为输入并解析它的结果生成一个 JavaScript 对象。为什么要搞得这么模棱两可?为什么不调用这个方法 toObject()?
【解决方案2】:

您的代码部分:

res => res.json()

是一个ES6 arrow function,翻译成:

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

关于json() 函数:

Body mixin 的json() 方法接受一个响应流和 读完。它返回一个用 将正文文本解析为 JSON 的结果。

阅读更多here

【讨论】:

    【解决方案3】:

    Javascript fetch 函数从指定的url 异步拉取资源。同时fetch 返回PromisePromise 帮助处理异步部分,并在使用获取的资源作为参数加载资源后运行传递给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()也可以写成(but not exactly equal)

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

    【讨论】:

      猜你喜欢
      • 2017-02-28
      • 2018-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-27
      • 2015-07-15
      • 2018-07-17
      • 2012-08-13
      相关资源
      最近更新 更多