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

Ani*_*ngh 6 javascript jsx react-native fetch-api

then(res => res.json())react-native提取中的以下代码段是什么意思?

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

Got*_*ttZ 8

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


Duc*_*lan 6

您的代码部分:

res => res.json()
Run Code Online (Sandbox Code Playgroud)

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

function(res){
    return res.json();
}
Run Code Online (Sandbox Code Playgroud)

并且,关于该json()功能:

Body mixin 的方法json()接受一个 Response 流并读取它完成。它返回一个承诺,该承诺将正文文本解析为 JSON 的结果进行解析。

在这里阅读更多内容。