以下片段中的then(res => res.json())是什么意思在react-native fetch中?在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 
     }); 

您的代码部分:

res => res.json() 

ES6 arrow function,其被翻译成:

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

而且,关于json()功能:

json()方法正文mixin需要响应流和 将其读取完成。它返回一个承诺,将解析正文文本的结果作为JSON解析为 。

了解更多here

Javascript fetch函数异步地从指定的url中提取资源。同时fetch返回Promise。 Promise可以帮助执行异步部分,并在资源以获取的资源作为参数加载后运行传入thenres => 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()} 

 

Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐