React-Native Fetch网络请求的简单封装

在react-native开发中,使用Fetch进行网络请求。官方文档上的网络请求

基本使用方法

GET请求

fetch(@"http://www.baidu.com")
  .then((response) => response.json()) .then((responseJson) => { console.log(responseJson);//打印返回的数据 }); }) .catch((error)=>{ console.log(error);//打印报的错 })

catch住fetch可能抛出的异常,否则出错时你可能看不到任何提示。

POST请求

Fetch还有可选的第二个参数,可以用来定制HTTP请求一些参数。你可以指定header参数,或是指定使用POST方法,又或是提交数据等等:

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

如果你的服务器无法识别上面POST的数据格式,那么可以尝试传统的form格式:

fetch('https://mywebsite.com/endpoint/',{
  method: 'POST',headers: {
    'Content-Type': 'application/x-www-form-urlencoded',body: 'key1=value1&key2=value2'
})

可以参考Fetch请求文档来查看所有可用的参数。

简单封装

GET

/* * get请求 * url:请求地址 * params:参数 * callback:回调函数 * */
    static get(url,params,callback){
        if (params) {
            let paramsArray = [];
            //拼接参数
            Object.keys(params).forEach(key => paramsArray.push(key + '=' + params[key]))
            if (url.search(/\?/) === -1) {
                url += '?' + paramsArray.join('&')
            } else {
                url += '&' + paramsArray.join('&')
            }
        }
        //fetch请求
        fetch(url,{
            method: 'GET',})
            .then((response) => {
                callback(response)
            })
            .catch((error) => {
                alert(error)
            });
    }

POST

post有两种形式:

  • 第一种:’Content-Type’: ‘application/json’
/*
     *  post请求
     *  url:请求地址
     *  params:参数,这里的参数格式是:{param1: 'value1',param2: 'value2'}
     *  callback:回调函数
     * */
    static postJSON(url,params,callback){
        //fetch请求
        fetch(url,{
            method: 'POST',headers: {
              'Accept': 'application/json',body:JSON.stringify(params)
        })
            .then((response) => response.json()) .then((responseJSON) => { callback(responseJSON) }) .catch((error) => { console.log("error = " + error) }); }
  • 第二种: form表单形式
/*
     *  post请求
     *  url:请求地址
     *  params:参数,这里的参数要用这种格式:'key1=value1&key2=value2'
     *  callback:回调函数
     * */
    static postForm(url,headers: {
                'Content-Type': 'application/x-www-form-urlencoded',body: params
        })
            .then((response) => response.json()) .then((responseJSON) => { callback(responseJSON) }) .catch((error) => { console.log("error = " + error) }); }

调用

//post请求
        let params = {'key1':'value1','key2':'value2'};
        NetRequest.postJSON('http://www.baidu.com/',function (set) {
            //下面的就是请求来的数据
            console.log(set)
        })

//get请求,以百度为例,没有参数,没有header
       NetRequest.get('https://www.baidu.com/','',function (set) {
            //下面是请求下来的数据
            console.log(set)
        })

解释一下:

//将JSON数据转换成字符串
JSON.stringify(params)

//将数据JSON化 JSON.parse(responseJSON)

相关文章

react 中的高阶组件主要是对于 hooks 之前的类组件来说的,如...
我们上一节了解了组件的更新机制,但是只是停留在表层上,例...
我们上一节了解了 react 的虚拟 dom 的格式,如何把虚拟 dom...
react 本身提供了克隆组件的方法,但是平时开发中可能很少使...
mobx 是一个简单可扩展的状态管理库,中文官网链接。小编在接...
我们在平常的开发中不可避免的会有很多列表渲染逻辑,在 pc ...