react-native fetch 中的 'then(res => res.json())' 是什么意思?

What does 'then(res => res.json())' in react-native fetch mean?

下面代码片段中的 then(res => res.json()) 在 react-native fetch 中是什么意思?

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

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

获取 returns 一个 object as Promise,其中包含各种信息,例如 headers、HTTP 状态等

您有 res.json() 和其他各种可能性。 .json() 将只是 return body 作为 json 内容的承诺。

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

您可以return数据如下:

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

您的代码部分:

res => res.json()

是一个ES6 arrow function,翻译成:

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

并且,关于 json() 函数:

The json() method of the Body mixin takes a Response stream and reads it to completion. It returns a promise that resolves with the result of parsing the body text as JSON.

阅读更多here

Javascriptfetch function asynchronously pulls a resource from the specified url. Meanwhile fetch returns a PromisePromise 帮助处理异步部分,并在资源以获取的资源作为参数加载后运行传递给 then (res => res.json()) 的函数。如果获取的资源是 JSON 格式,则可以使用 json() 进行解析。

then 也 returns 一个 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()}