添加布尔量的React Native fetch网络请求库。

这里我对React Native中的fetch网络请求做了一个小小的封装。在回调函数中增加了一个布尔值来进行判断请求成功与否。同时我会在下面附上使用方法概要。如果写的有问题请多多指教

/**
 * 封装网络请求
 */
//使用带参数的post请求
export function postRequest(url, data, callback) {
    var method = {
        method: 'POST',
        headers: {
            'Accept': 'application/json'
        },
        body: JSON.stringify(data)
    }
    /*也可直接使用response.json()*/
    fetch(url, method)
        .then((response) => response.text())
        .then((responseText) => {
            //将返回的JSON字符串转成JSON对象,并传递到回调方法中
            callback(JSON.parse(responseText),true);
            console.log("NetFetch_Post:获得的json_text数据:" + responseText);
            console.log("NetFetch_Post:获得的json_text转换为json对象数据:" + JSON.parse(responseText));
        })
        .catch((error) => {
            callback(error,false);
            console.log("NetFetch_Post:responseError:" + error);
        });
}

/*使用get方式进行网络请求,传入url*/
export function getRequest(url, callback) {
    fetch(url)
        .then((response)=>response.text())
        .then((responseText)=> {
            callback(JSON.parse(responseText),true);
            console.log("NetFetch_Get:获得的json_text数据:" + responseText);
            console.log("NetFetch_Get:获得的json_text转换为json对象数据:" + JSON.parse(responseText));
        })
        .catch((error) => {
            callback(error,false);
            console.log("NetFetch_Get:responseError:" + error);
        });
}

导入方法

import {postRequest,getRequest} from '../Net/NetFetch'

ES5使用方式。需要添加bind(this)

getRequest(url,function(data,isSuccess){
            console.log("ES5 the net response:"+isSuccess);
            if(isSuccess){
                this.setState({
                    json1: data
                });
            }else{
                 console.log("error:"+data);
            }
        }.bind(this));

使用ES6的写法

getRequest(url_left,(data,isSuccess)=>{
            console.log("ES6 the net response:"+isSuccess);
            if(isSuccess){
                this.setState({          
                    json1: data
                });
            }else{
                console.log("error:"+data);
            }
        })

觉得可以的话,就给个赞赏吧!
这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Auspicious5

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值