React Native入门(八)之网络请求Fetch
前言最近有些事情要忙,RN相关的内容没有更新,现在就来了解一下RN中进行网络请求相关的内容! 介绍React Native提供了和web标准一致的Fetch API,用于满足开发者访问网络的需求。 使用FetchFetch API 提供一个 fetch('https://facebook.github.io/react-native/movies.json')
Fetch API 是基于
好了,知道了这些之后,我们来说一下如果处理网络请求返回的结果! Fetch 方法会返回一个 好,下面看一个例子,也是RN中文网的例子,这里做了一些改动! {
"title": "The Basics - Networking","description": "Your app fetched this from a remote endpoint!","movies": [ { "title": "Star Wars","releaseYear": "1977"},{ "title": "Back to the Future","releaseYear": "1985"},{ "title": "The Matrix","releaseYear": "1999"},{ "title": "Inception","releaseYear": "2010"},{ "title": "Interstellar","releaseYear": "2014"} ] }
这个一个请求到一些电影信息的json数据。 class NetText extends Component {
constructor(props) { //构造器
super(props);
this.state = { //定义的三个状态
title: '',description: '',movies: ''
};
}
//列表点击事件
itemClick(item,index) {
alert('点击了第' + index + '项,电影名称:' + item.title + '上映年份:' + item.releaseYear);
}
//FlatList的key
_keyExtractor = (item,index) => index;
//子item渲染
_renderItem = ({item,index}) => {
return (
<TouchableOpacity activeOpacity={0.5} onPress={this.itemClick.bind(this, item,index)}> //这里index为奇偶数给不同的背景 <View style={[WebTestStyles.item, {backgroundColor: index % 2 == 0 ? 'lightgray' : 'whitesmoke'}]}> <Text style={WebTestStyles.itemTitle}>{item.title}</Text> <Text style={WebTestStyles.itemYear}>上映年份:{item.releaseYear}</Text> </View> </TouchableOpacity> ); } //列表分割线 _itemDivide = () => { return ( <View style={{height: 1,backgroundColor: 'dimgray'}}/> ); } //getMoviesFromApiAsync() { _fetchData = () => { fetch('https://facebook.github.io/react-native/movies.json') .then((response) => response.json())//把response转为json格式 .then((jsondata) => { //上面的转好的json //alert(jsondata.movies[0].title); this.setState({ //将获取到的数据更新到state中 title: jsondata.title,description: jsondata.description,movies: jsondata.movies,}) }) .catch((error) => { console.error(error); }); }; render() { return ( <View style={WebTestStyles.container}> <Text style={WebTestStyles.title}>{this.state.title}</Text> <Text style={WebTestStyles.description}>{this.state.description}</Text> <FlatList //列表组件 style={{marginTop: 20}} data={this.state.movies} keyExtractor={this._keyExtractor} renderItem={this._renderItem} ItemSeparatorComponent={this._itemDivide}/> <Button title="请求网络" onPress={this._fetchData}/> </View> ); } } ; const WebTestStyles = StyleSheet.create({ container: { flex: 1,flexDirection: 'column' },title: { fontSize: 20,fontWeight: 'bold',alignSelf: 'center' },description: { fontSize: 12,item: { padding: 10 },itemTitle: { fontSize: 18,fontWeight: 'bold' },itemYear: { fontSize: 16,} })
然后看一下效果: 代码的话,基本上没有什么好说的,就是点击一个按钮去请求网络,然后拿到json格式的数据,两个文本字段,一个数组,然后把数组设置为FlatList的data,将电影以列表形式展示! Fetch相关API请求参数的设置上面我们在请求网络的时候,只是用
类似这样: fetch('https://mywebsite.com/endpoint/',{ method: 'POST',headers: { 'Accept': 'application/json','Content-Type': 'application/json',},body: JSON.stringify({ firstParam: 'yourValue',secondParam: 'yourOtherValue',}) })
如果你的服务器无法识别上面POST的数据格式,那么可以尝试传统的form格式,示例如下: fetch('https://mywebsite.com/endpoint/',{
method: 'POST',headers: {
'Content-Type': 'application/x-www-form-urlencoded',body: 'key1=value1&key2=value2'
})
这个得话,就需要和做后台的同事提前沟通好就行了! 自定义Header关于请求头Header的话,还可以通过 Headers() 构造函数来创建一个你自己的 headers 对象。 var myHeaders = new Headers();
myHeaders.append("Content-Type","text/plain");
myHeaders.append("Content-Length",content.length.toString());
myHeaders.append("X-Custom-Header","ProcessThisImmediately");
也可以传一个多维数组或者对象字面量: myHeaders = new Headers({
"Content-Type": "text/plain","Content-Length": content.length.toString(),"X-Custom-Header": "ProcessThisImmediately",});
自定义Request除了上面的用法,我们还可以通过使用 var url='https://mywebsite.com/endpoint/';
var myOptions = { method: 'GET',headers: myHeaders,mode: 'cors',cache: 'default' };
var myRequest = new Request(url,myOptions );
fetch(myRequest)
.then()
...
Response属性:
方法:
其他方法:
上边就是Fetch常用的API,其他的API可以参考Fetch_API,也就是上边的网站! 参考文章: (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |