RN-Fetch

2017-07-14  本文已影响281人  hliccy

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 无法查看请求的进度
上一篇下一篇

猜你喜欢

热点阅读