RN 网络请求
react native提供了fetch和XMLHttpRequest(即aiax)两种网络请求方式,但是ajax的配置和调用方式比较混乱,不符合指责分离的原则,基于时间的一步模型的写法,没有采用Promise的fetch简洁,所以强烈建议使用fetch网络请求的用法。
fetch
fetch使用链式调用的方式来进行操作,fetch的基本格式
fetch(url , fetchOptions)
.then((response) => {
...//数据解析方式
})
.then((responseData) => {
...//获取到的数据处理
})
.catch((error) => {
...//错误处理
})
.done(); //千万不要忘记哟
发起网络请求
上述示例的第一行fetch(url , fetchOptions)为发起网络请求的写法。
fetch(url)为发起网络请求的最简单的写法,只传入一个参数,默认的为GET方式请求,将网址作为参数传入fetch 的方法,如:
fetch('https://mywebsite.com/mydata.json')
fetch还有可选的第二个参数,即示例中的fetchOptions,它可以用来定制Http请求的一些参数,如指定header参数、GEt或POST方法、提交表单数据等。例如:
let fetchOptions = {
method:'POST',
headers:{
'Accept':'application/json',
'Content-Type':'application/json',
},
body:JSON.stringify({
firstParam:'yourValue',
secondParam:'yourOtherValue',
})
};
fetch(url , fetchOptions);
fetchOptions是一个对象,它包含了如下可选的参数设置:
- method : 请求方式:GET、POST、PUT等
- headers : 请求头
- body : 需要发送的数据
- mode : 控制是否允许跨域 :sors 、no-cors 、same-origin
- cache : 缓存设置 : default、no-store 、no-cache 、 force-cache 、 or only-if-cached
参数解释
1、headers请求头遵循http协议规范,通常设置Accept、Content-Type属性。
Accept:希望接受的数据类型
Content-Type:发送的实体数据的数据类型
2、body的传入参数有三种方式:headers: { 'Accept' : 'application/json', 'Content-Type' : 'application/json', }
方式一:不推荐,可能在某些服务器无法识别。
JSON.stringify({key:value1 , key2:value2 , ...})
方式二:传统的form格式
'key1 = value1 & key2 = value2'
方式三:使用FormData
let formData = new FormData();
formData.append("key1" , "value1");
formData.append("key2" , "value2");
3、mode:控制属否允许跨域:
- same-origin: 同源请求,该模式是不允许跨域的,跨域回报error。
- cors: 允许跨域请求,可以获取第三方数据,前提是所访问的服务允许跨域访问。
- no-cors:默认mode。该模式允许发送本次跨域请求,但是不能访问响应返回的内容,即可以请求其他域的脚本、图片和其他资源,但是不能访问response里面的属性。
如下是一个采用post方式的网络请求:
let formData = new FarmData();
formData.append("key1" , "value1");
formData.append("key2" , "value2");
fetch(url , {
method:"POST",
headers:{
"Accept" : "application/json",
"Content-Type" : "application/json",
},
body:formData,
})
处理服务器的响应数据
fetch由于采用了promise的一步处理方式,因此在写网络请求这种异步操作时他别简单顺滑。
fetch(url , fetchOptions)
.then((response) => response.json()) //数据解析方式,获取到网络请求返回的对象
.then((responseJson) => { //网络请求成功,处理获取到的数据
return responseJson.movies;
})
.catch((error) => { //网络请求失败,错误处理,否则网络请求失败是无法看到错误信息
console.error(error);
})
实例
下面结合
前面介绍的生命周期及State、Props的知识,演示一个网络数据资源一列表的形式显示出来的实例。
1、渲染加载中的界面
在获取真实的网络数据之前,我们的界面要现实一个加载中的Text,并设置其样式。
import React, {Component} from "react";
import {
Text,
Image,
View,
StyleSheet,
}from 'react-native';
export default class FetchNetDataDemo extends Component {
render() {
return (
<Text style={Styles.loading}>加载中...</Text>
)
}
}
const Styles = StyleSheet.create({
loading:{
textAlign: "center",
fontSize: 16,
padding: 20
},
})
2、获取网络数据
下面用fetch网络请求获取网上一本真实的书本信息。在组件的生命周期中,组件初始阶段有constructor开始,一般都在这是初始化一些信息。
constructor(props) {
super(props);
this.state = {
bookinfo: null
};
}
组件在渲染
render后会主动调用componentDidMount函数,componentDidMount方法只会在组件完成后加载一次。我们在componentDidMount中执行获取网络数据的方法fetchBookinfoList,修改组件状态:fetchBookinfoList() { const url = 'https://api.douban.com/v2/book/isbn/9787302315582'; fetch(url) .then((response)=>response.json()) .then( (responseJson)=> { let bookinfo = responseJson; console.log(bookinfo); this.setState({ bookinfo: bookinfo, }) } ) .catch((error)=>console.error(error)) } componentDidMount() { this.fetchBookinfoList(); }
3、将获取到的网络数据显示在界面上
修改render()方法,当this.state.bookinfo数据不为空时显示书本信息,否则显示一个正在加载的视图。
render() { let item = this.state.bookinfo; if (item) { return this.renderItem(item); }else { return ( <Text style={Styles.loading}>加载中...</Text> ) } } renderItem(item) { return ( <View style={Styles.container}> <Image style={Styles.image_book} source={{uri: item.image}}/> <View style={Styles.right}> <Text style={Styles.text_title}>{item.title}</Text> <Text style={Styles.text_price}>{item.publisher}</Text> </View> </View> ) }
Fetch的轻量级封装
这里我们用Promise进行封装:
export default class HttpUtils{
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);
})
})
}
}
调用:
// GET HttpUtils.get(url) .then(result=>{ this.setState({ result:JSON.stringify(result) }) }) .catch(error=>{ this.setState({ result:'err+' + JSON.stringify(error) }) })
// POST
HttpUtils.post(url,data)
.then(result=>{
this.setState({
result:JSON.stringify(result)
})
})
.catch(error=>{
this.setState({
result:'err + ' + JSON.stringify(error)
})
})

浙公网安备 33010602011771号