这里我对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);
}
})
觉得可以的话,就给个赞赏吧!