啥也不說了直接記錄代碼吧
fetch('https://facebook.github.io/react-native/movies.json',{
method:'GET',//如果為GET方式,則不要添加body,否則會出錯(cuò) GET/POST
header:{//請求頭
},
// body:{//請求參數(shù)
// 'key1':'value1',
// 'key2':'value2'
// }
})
.then((response) => response.json())//將數(shù)據(jù)轉(zhuǎn)成json,也可以轉(zhuǎn)成 response.text、response.html
.then((responseJson) => {//獲取轉(zhuǎn)化后的數(shù)據(jù)responseJson、responseText、responseHtml
/*return responseJson.movies; */
console.log(responseJson);
}).catch((error) => {
console.log(error);
});
所有的代碼就這么多,比起iOS來少的不是一星半點(diǎn)啊,超級簡單
當(dāng)然啦,喜歡封裝的自然少不了封裝一下下,下面也僅僅是簡單簡單簡單的封裝了一小下而已
注釋的也是很6的
FetchRequest
/**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
TouchableOpacity
} from 'react-native';
export default class FetchRequest extends Component {
//定義接收請求地址,當(dāng)然也可以添加請求參數(shù)
//parames 盡量是{'key1':'value1','key2':'value2'}
//static request(url,parames,callBackSuccess,callBackError){
static request(url,loadCallBack,callBackSuccess,callBackError){
//請求發(fā)送中回調(diào),可以加一些loading效果
loadCallBack();
fetch(url,{
method:'GET',//如果為GET方式,則不要添加body,否則會出錯(cuò) GET/POST
header:{//請求頭
},
// body:parames//請求參數(shù)
})
.then((response) => response.json())//將數(shù)據(jù)轉(zhuǎn)成json,也可以轉(zhuǎn)成 response.text、response.html
.then((responseJson) => {//獲取轉(zhuǎn)化后的數(shù)據(jù)responseJson、responseText、responseHtml
/*return responseJson.movies; */
//成功回調(diào)
callBackSuccess(JSON.stringify(responseJson));//JSON.stringify()避免出現(xiàn)煩人的[object object]
}).catch((error) => {
//失敗回調(diào)
callBackError(error);
});
}
}
使用就更簡單了
import Request from './FetchRequest'
request(){
//調(diào)用封裝起來的方法
Request.request('https://facebook.github.io/react-native/movies.json',
()=>{
console.log('請求發(fā)送中...')
},
(responseData)=>{
this.requestSuccess(responseData);
},
(error)=>{
this.requestError(error);
})
}