美文网首页
React-Native爬坑中(网络层简单封装)

React-Native爬坑中(网络层简单封装)

作者: 逗留 | 来源:发表于2017-09-06 15:49 被阅读112次

    即将开始RN的深入坑,总结一下以前用到的一些点滴。。。

    在RN中使用网络请求,一般会使用fetch来做,fetch具体用法:https://github.com/github/fetch https://segmentfault.com/a/1190000008484070,为了使用更加方便,做一个简单的封装,大体意思是这样,具体细节命名之类可根据需要修改。

    首先,针对接口API,定义如下(const和get都是为了避免被调用者修改):

    const BaseUrl = "http://www.baidu.com/";
    const Api = {
        get GETPRICEBASEDATAAPI() {return BaseUrl + 'app/order/warehouse'},
        get CALCULATEPRICEAPI() {return BaseUrl + 'app/utility/priceCalculation/appcalculation'},
    ...
    };
    
    

    针对请求状态,定义如下:

    
    const Process = {
        get FETCH_BEGIN() {return 'FETCH_BEGIN'},//请求开始
        get FETCH_SUCCESS() {return 'FETCH_SUCCESS'},//请求成功
        get FETCH_FAIL() {return 'FETCH_FAIL'}//请求失败
    };
    
    

    针对响应结果,定义如下:

    class Response {}
    Response.protoTypes = {
        code: Number, //状态码
        msg: String, //消息
        data: Array //数据(这里假设所有接口返回结果都是数组形式)
    };
    
    

    准备工作做完后,开始启动fetch,其中的方法均使用静态方法(类方法)

    class Net {
    //首先定义最常使用的get和post,其中参数api为接口地址,params为请求参数,callback为请求结果的回调,在回调函数中传递Response
    
    static commonSendGet(api, params, callback) {
            return this.commonSend('GET', api, params, callback);
        }
    
    static commonSendPost(api, params, callback) {
            return this.commonSend('POST', api, params, callback);
        }
    
    static commonModel(method, api, params, callback) {
            if (method === 'GET') {
                api = this.generateApi(method, api, params);
            }
    
            let setting = this.generateSetting(method, api, params);
    
            return fetch(api, setting)
                .then(response => {
                    return response.json();
                })
                .then(json=>{
                    this.dealWithJson(json, callback);
                })
                .catch(e=>{
                    this.dealWithJson(null, callback);
                })
        }
    
    //对api进行处理
    static generateApi(method, api, params) {
            if (method === 'GET') {
                api = this.appendParams(api, params);
            }
            return api;
        }
    
    //设置请求(请求头,请求体等),主动保存或设置cookies,需要调用原生来设置,或者使用社区中提供的[react-native-cookiemanager](https://github.com/beefe/react-native-cookiemanager)
    static generateSetting(method, api, params) {
            let setting = {};
            setting.credentials = 'same-origin'; //同域发送cookies
            //setting.credentials = 'include'; //跨域+同域发送cookies
            setting.method = method;
            if (method === 'POST') {
                setting.body = JSON.stringify(params);
            }
            let headers = this.setNetHeaders(api);
            if (headers) setting.headers = headers;
            return setting;
        }
    
    //设置请求头
    static setNetHeaders(api) {
            if (api.match(Api.CALCULATEPRICEAPI)) {
                return {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                }
            }
            return  null;
        }
    
    //处理请求结果,并执行回调函数
    static dealWithJson(json, callback) {
            let res = this.generateResponse(json);
            this.sendCallback(res, callback);
        }
    
    //将请求到的json数据转化为Response
        static generateResponse(json) {
            let res = new Response();
            if (!json) {
                res.code = 1;
                res.msg = '网络错误';
                return res;
            }
            res.code = json.status;
            res.data = json.data;
            res.msg = this.generateMsg(json);
            return res;
        }
    
    //处理返回的消息
        static generateMsg(json) {
            if (!json) return null;
            return json.msgs;
        }
    
    //执行回调函数
        static sendCallback(res, callback) {
            if (callback) callback(res);
        }
    }
    //最后,将其暴露给其它文件调用
    export {Net, Process, Api, Response};
    
    

    以上简单封装告一段落,接下来在其它地方使用的时候,会变成这样(以redux中的action为例):

    import {Net, Process, Api, Response} from '../net/net';
    import Type from './type'; //这个代表action的标示,后面说到redux的时候再细说
    
    const calculatePrice = (params) => (dispatch, getState) => {
        dispatch({type: Type.CALCULATEPRICE, name: Process.FETCH_BEGIN});
        return Net.commonSendPost(Api.CALCULATEPRICEAPI, params, (res)=>{
            if (res.code == 0 || res.code == 999) {
                dispatch({type: Type.CALCULATEPRICE, name: Process.FETCH_SUCCESS, payload: res.data, msg: res.msg})//res.data
            } else {
                dispatch({type: Type.CALCULATEPRICE, name: Process.FETCH_FAIL, payload: null, msg: res.msg})
            }
        })
    };
    
    const getPriceBaseData = () => (dispatch, getState) => {
        dispatch({type: Type.GETPRICEBASEDATA, name: Process.FETCH_BEGIN});
        return Net.commonSendGet(Api.GETPRICEBASEDATAAPI, null, (res)=>{
            if (res.code == 0 || res.code == 999) {
                dispatch({type: Type.GETPRICEBASEDATA, name: Process.FETCH_SUCCESS, payload: res.data, msg: res.msg})//res.data
            } else {
                dispatch({type: Type.GETPRICEBASEDATA, name: Process.FETCH_FAIL, payload: null, msg: res.msg})
            }
        })
    };
    
    export {changePriceParams, calculatePrice, getPriceBaseData};
    

    相关文章

      网友评论

          本文标题:React-Native爬坑中(网络层简单封装)

          本文链接:https://www.haomeiwen.com/subject/wahvjxtx.html