网络封装
/**
* 网络请求工具类
* Songlcy create
* params:请求参数
* successCallback:成功回调
* failCallback:失败回调
*/
import RootToast from '../pages/RootToast/RootToast'
var host = 'https://.do';
import ShowProgress from '../pages/ProgressHUD/ShowProgress';
let showProgress = new ShowProgress;
let Network = {
postNetwork: (params,successCallBack, failCallBack)=> {
if(params.isProgress === '1' ){
showProgress.show();
}
console.log('***********************网络请求报文******************************');
console.log( JSON.stringify(params));
console.log('================================================================');
paramStr = 'transCode=' + params.transCode + '&requestBodyJson=' + JSON.stringify(params.request);
fetch(host,
{
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
"Cookie":JSON.stringify({})
},
body: paramStr
}
).then((response) => {
showProgress.hidden();
if (response.ok) {
return response.json();
} else {
RootToast.show('服务器连接异常');
}
}).then((response) => {
console.log('***********************成功返回****************************');
console.log( JSON.stringify(response));
console.log('================================================================');
if (response.responseBody == null) {
RootToast.show(response.errorMsg);
if (failCallBack && typeof(failCallBack) == 'function'){
failCallBack(response);
}
} else {
successCallBack(response);
}
}).catch((error) => {
showProgress.hidden();
console.log(error.message);
if (failCallBack && typeof(failCallBack) == 'function') {
failCallBack(error);
}
})
}
}
export default Network;
提示
/**
* RootToast.js
*/
import Toast from 'react-native-root-toast';
let RootToast = {
toast:null,
show:(msg)=>{
this.toast = Toast.show(msg,{
position:0,
duration:1500
})
}
}
export default RootToast;
/**
* ShowProgress.js
*/
import React,{Component} from 'react'
import RootSiblings from 'react-native-root-siblings';
import ProgressHUD from './ProgressHUD';
let sibling = null;
export default class ShowProgress{
show(){
sibling = new RootSiblings(<ProgressHUD />);
}
hidden(){
if(sibling instanceof RootSiblings){
sibling.destroy();
}
}
}
环形提示
/**
* ProgressHUD.js
*/
import React, {Component} from 'react';
import {
View,
Dimensions,
StyleSheet,
Platform
}from 'react-native';
import * as Progress from 'react-native-progress'
const {width, height} = Dimensions.get('window')
export default class ProgressHUD extends Component {
render(){
return(
<View style={styles.baseViewStyle}>
<View style={styles.backViewStyle}>
<Progress.Circle size={width/8} indeterminate={true} />
</View>
</View>
);
}
}
const styles = StyleSheet.create(
{
baseViewStyle:{
position:'absolute',
top:(Platform.OS=='ios')?64:44,
height:(Platform.OS=='ios')?height-64:height-44,
width:width,
alignItems:'center',
backgroundColor:'rgba(0,0,0,0.2)'
},
backViewStyle:{
backgroundColor:'white',
width:width/4,
height:width/4,
borderRadius:10,
justifyContent:'center',
alignItems:'center',
marginTop:height/4
}
}
);
本地存储
/**
* LocalStorage.js
*/
let LocalStorage = {
/**
* 保存数据到本地
* key:数据存储key
* params:请求参数
*/
saveDataToLocal: (key,params)=> {
global.localStorage.save({
key: key,
rawData: params,
expires: null
});
},
/**
* 从本地读取数据
* key:数据存储key
* successCallback:成功回调方法
* failCallback:失败回调方法
*/
loadDataFromLocal:(key,successCallback,failCallback)=>{
global.localStorage.load({
key: key,
}).then(ret => {
successCallback(ret);
}).catch(err => {
switch (err.name) {
case 'NotFoundError':
// TODO;
successCallback("");
break;
case 'ExpiredError':
// TODO
break;
}
})
}
}
export default LocalStorage;
调用网络请求
/**
* Main.js
*/
import React, {Component} from 'react';
import {
StyleSheet,
Text,
View,
Image,
Navigator,
AsyncStorage
} from 'react-native';
import TabNavigator from 'react-native-tab-navigator';
import HomeView from './Home.js';
import EnjoyView from './Enjoy.js';
import LifeView from './Life.js';
import Storage from 'react-native-storage';
import LocalStorage from '../../LocalStorage/LocalStorage';
import Network from '../../Network/Network'
export default class Main extends Component {
constructor(props) {
super(props);
this.state = {selectedTab: 'home'};
}
componentDidMount() {
var storage = new Storage({
size: 1000,
storageBackend: AsyncStorage,
defaultExpires:null,
enableCache:true,
sync : {
// we'll talk about the details later.
}
});
global.localStorage = storage;
//本地存储accessToken
var accessToken = '0af25eb6666aebf2a3f561b7a174311453204fb9c789a64b3934975cb6b5d13b9166f614785a0b41';
LocalStorage.saveDataToLocal('accessToken', accessToken);
//查询用户信息
let params = {
transCode: 'T1004',
request: {
loginName: '13020130525',
accessToken: accessToken
}
};
Network.postNetwork(params, this.successCallBack, this.failCallBack);
}
successCallBack(data) {
LocalStorage.saveDataToLocal('userInfo', data.responseBody.user);
LocalStorage.saveDataToLocal('myCarList', ['footer']);
/*
userInfo的格式
{"loginName":"13020130525",
"userName":"周舫旭",
"idType":"1",
"idNumber":"410381199004214033",
"telphone":"13020130525",
"email":"2222@163.com",
"recommendMobile":null,
"recommendTimes":0,
"certFlag":"1",
"headPicPath":null,
"nickName":null,
"gender":"0",
"userId":27377,
"address":"2222222",
"branchCompany":"3010100",
"postcode":"123545",
"province":"上海&2",
"city":"上海&201",
"area":"长宁区&20101",
"registerFlag":"1",
"headImgBase64":null}
*/
}
failCallBack(data) {
//console.log(data);
}
render() {
return (
<TabNavigator >
{this.creatTabItem('home', '优保障',
require('../../image/icon/iconnavi1.png'),
require('../../image/icon/icon-navi-1-cur.png'),
styles.homeSelectStyle,
<HomeView navigator={this.props.navigator}/>
)}
{this.creatTabItem('enjoy', '享服务',
require('../../image/icon/icon-navi-2.png'),
require('../../image/icon/icon-navi-2-cur.png'),
styles.enjoySelectedStyle,
<EnjoyView navigator={this.props.navigator}/>
)}
{this.creatTabItem('life', '汇生活',
require('../../image/icon/icon-navi-3.png'),
require('../../image/icon/icon-navi-3-cur.png'),
styles.lifeSelectStyle,
<LifeView navigator={this.props.navigator}/>
)}
</TabNavigator>
);
}
creatTabItem(selected, title, renderIcon, selectedIcon, selectedTitleStyle, childView) {
return (
<TabNavigator.Item selected={this.state.selectedTab === selected}
title={title}
renderIcon={() => <Image source={renderIcon} style={styles.iconStyle}/>}
renderSelectedIcon={() => <Image source={selectedIcon} style={styles.iconStyle}/>}
selectedTitleStyle={selectedTitleStyle}
onPress={() => this.setState({selectedTab: selected})}>
{childView}
</TabNavigator.Item>
);
}
}
const styles = StyleSheet.create({
homeSelectStyle: {
color: '#005bac'
},
enjoySelectedStyle: {
color: '#009ddc'
},
lifeSelectStyle: {
color: 'orange'
},
iconStyle: {
width: 25,
height: 30,
resizeMode: 'contain'
}
});