RN-Fetch

Fetch

fetch(url, options)

Return a 'Promise'

url : eg 'http://www.baidu.com'

Options

{
    method: 'GET'
    , headers: {}        // request header. format {a:'1'} or {b:['1','2','3']}
    , redirect: 'follow' // set to `manual` to extract redirect headers, `error` to reject redirect
    , follow: 20         // maximum redirect count. 0 to not follow redirect
    , timeout: 0         // req/res timeout in ms, it resets on redirect. 0 to disable (OS limit applies)
    , compress: true     // support gzip/deflate content encoding. false to disable
    , size: 0            // maximum response body size in bytes. 0 to disable
    , body: empty        // request body. can be a string, buffer, readable stream
    , agent: null        // http.Agent instance, allows custom proxy, certificate etc.
}

基本使用

无参数

fetch('http://www.baidu.com')

有参数

fetch('/edit', {
    method:'POST',
    headers:{
    'Accept': 'application/json',
    'Content-Type': 'application/json',
    },
     body: JSON.stringify({
    firstParam: 'yourValue',
    secondParam: 'yourOtherValue',
  })
})

实例:请求商品列表

onLoad (url){

    //url = 'http://ip/api/shangpin'

    let  params = {
        'token':'05F51D2E-EC1B-4F2E-9E4A-9346A79A4B91',
        'verson':'1.0.0',
        'from':'0',
        'tenantcode':1,
        'page':1,
        'rows':20,
        'shopcode':'201701'
    };

    let arrParam = [];

    // 拼接请求参数到 url
    Object.keys(params).forEach(key=> arrParam.push(key + '=' + params[key]))
    if (url.search(/\?/) === -1) {
        url += '?' + arrParam.join('&')
    } else {
        url += '&' + arrParam.join('&')
    }

    fetch(url, {
        method: 'GET',

    })
        .then((response) => response.json()) // 第一次 stream 转 json
        .then((json)=>{
            this.setState({
                items: json.data.rows,
            });
        })
        .catch((error)=>{

        })
}

*注 Fetch缺点

* fetch 不支持同步请求
* fetch 不支持取消一个请求
* fetch 无法查看请求的进度
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,026评论 19 139
  • 本文内容 fetch设置超时时间 所需知识点:Promise.race 这次百米赛跑,我允许你先跑30秒,30秒内...
    精神病患者link常阅读 2,335评论 0 1
  • 1、打开目录 /xxxx/node_modules/whatwg-fetch/fetch.js 然后在我们调用的时...
    亦晴工作室阅读 1,142评论 0 0
  • ¥开启¥ 【iAPP实现进入界面执行逐一显】 〖2017-08-25 15:22:14〗 《//首先开一个线程,因...
    小菜c阅读 6,593评论 0 17
  • 多少次拿起电话 却不知道打给谁 多少个深夜想起她 却又深知她不可能会听见 在别人面前俨然我早已是个大人了 而在她哪...
    琴汐阅读 2,104评论 0 1