在ReactNative
使用Fetch
,不需要安裝鸿脓,是一個(gè)全局的,直接使用即可
1味赃、使用get請求獲取數(shù)據(jù)
<View style={styles.container}>
<Text style={{fontSize:20}} onPress={()=>this.onLoad('http://rap.taobao.org/mockjsdata/11793/test')}>獲取數(shù)據(jù)</Text>
<Text>得到的數(shù)據(jù):{this.state.result}</Text>
</View>
當(dāng)點(diǎn)擊獲取數(shù)據(jù)
的時(shí)候請求網(wǎng)絡(luò)地址,調(diào)用onLoad
方法心俗,代碼如下:
onLoad(url){
fetch(url)
.then(response=>response.json())
.then(result=>{
this.setState({
result:JSON.stringify(result)
})
})
.catch(error=>{//捕獲異常
this.setState({
result:JSON.stringify(error)
})
})
}
在這之前要先初始化result
為一個(gè)空字符串
constructor(props) {
super(props);
this.state = {result:''}
}
運(yùn)行截圖:
2城榛、使用POST提交數(shù)據(jù)态兴,模擬登陸
<View style={styles.container}>
<Text style={{fontSize:20}} onPress={()=>this.onSubmit('http://rap.taobao.org/mockjsdata/11793/submit',{userName:"小明",password:"123456"})}>提交數(shù)據(jù),模擬登陸</Text>
<Text>返回結(jié)果:{this.state.result}</Text>
</View>
點(diǎn)擊提交數(shù)據(jù)喘垂,模擬登陸
之后調(diào)用onSubmit
方法:
onSubmit(url,data){
fetch(url,{
method:'POST',
header:{
'Accept':"application/json",
'Content-Type':"application/json"
},
body:JSON.stringify(data)
})
.then(response=>response.json())
.then(result=>{
this.setState({
result:JSON.stringify(result)
})
})
.catch(error=>{
this.setState({
result:JSON.stringify(error)
})
})
}
1绍撞、使用Post
提交的時(shí)候,fetch
需要傳遞三個(gè)參數(shù)傻铣,第一個(gè)參數(shù)method
,第二個(gè)參數(shù)header
,第三個(gè)參數(shù)body
(即傳遞的數(shù)據(jù))
2、onSubmit
方法傳遞兩個(gè)參數(shù)鸭限,一個(gè)url
,一個(gè)是要傳遞的數(shù)據(jù)data
两踏,運(yùn)行截圖:
3、對Fetch的一個(gè)封裝
- 新建一個(gè)
HttpUtil.js
類
/**
* Created by Dell on 2018/3/7.
*/
export default class HttpUtil{
static get(url){
return new Promise((resolve,reject)=>{
fetch(url)
.then(response=>response.json())
.then(result=>{
resolve(result)
})
.catch(error=>{
reject(error)
})
})
}
static post(url,data){
return new Promise((resolve,reject)=>{
fetch(url,{
method:'POST',
header:{
'Accept':"application/json",
'Content-Type':"application/json"
},
body:JSON.stringify(data)
})
.then(response=>response.json())
.then(result=>{
resolve(result)
})
.catch(error=>{
reject(error)
})
})
}
}
- 使用的時(shí)候直接導(dǎo)入該類
import HttpUtil from './HttpUtil'
調(diào)用get方法
onLoad(url) {
HttpUtil.get(url)
.then(result => {
this.setState({
result: JSON.stringify(result)
})
})
.catch(error => {
this.setState({
result: JSON.stringify(error)
})
})
}
調(diào)用post方法
onSubmit(url, data) {
HttpUtil.post(url,data)
.then(result => {
this.setState({
result: JSON.stringify(result)
})
})
.catch(error => {
this.setState({
result: JSON.stringify(error)
})
})
}
相比之下,在封裝fetch
工具類之后,代碼減少了很多车荔,這樣代碼維護(hù)起來也很方便