ReactNative网络请求这部分很简单但也很重要只要知道web页面网络请求,这边也完全适应。这里通过代码家API结合ListView的使用来简单试用下fetch的get请求。
get请求
先看效果图
使用基本步骤:下面会贴出完整代码
1.在构造方法中初始化
/**
* 初始化数据
*/
constructor(props) {
super(props);
this.state = {
dataSource: new ListView.DataSource({
rowHasChanged: ((row1, row2) => row1 !== row2)
}),
load: false
}
}
2.通过componentDidMount()方法调用fetch加载数据并通过setState()方法刷新界面
/**
* 加载耗时操作
*/
componentDidMount() {
this.getDataFromFetch();
}
getDataFromFetch() {
fetch('http://gank.io/api/search/query/listview/category/福利/count/10/page/1')//请求地址
.then((response) => response.json())//取数据
.then((responseText) => {//处理数据
//通过setState()方法重新渲染界面
this.setState({
//改变加载ListView
load: true,
//设置数据源刷新界面
dataSource: this.state.dataSource.cloneWithRows(responseText.results),
})
})
.catch((error) => {
console.warn(error);
}).done();
}
3.重写renderRow()方法进行界面绘制
/**
* 重写renderRow
*/
renderRow(rowData) {
return (
<View style={{ flex: 1 }}>
<Image source={{ uri: rowData.url }}
style={{ width: width, height: height / 2, marginTop: 5 }}
/>
</View>
)
}
完整代码:
import React, {Component} from 'react';
import {
AppRegistry,
StyleSheet,
View,
Text,
TouchableOpacity,
ToastAndroid,
Image,
ListView,
} from 'react-native';
Dimensions = require('Dimensions');
width = Dimensions.get('window').width;
height = Dimensions.get('window').height;
class FetchG extends Component {
/**
* 初始化数据
*/
constructor(props) {
super(props);
this.state = {
dataSource: new ListView.DataSource({
rowHasChanged: ((row1, row2) => row1 !== row2)
}),
load: false
}
}
/**
* 渲染界面
*/
render() {
/**
* 因为数据时异步加载, 用load判断是否正在加载 如果加载完毕重新刷新界面改变load值
*/
if (!this.state.load) {
return <Text>加载中...</Text>
}
return (this.renderView(this.state.dataSource))
}
renderView() {
return (
<ListView
dataSource={this.state.dataSource}
renderRow={this.renderRow}
/>
)
}
/**
* 重写renderRow
*/
renderRow(rowData) {
return (
<View style={{ flex: 1 }}>
<Image source={{ uri: rowData.url }}
style={{ width: width, height: height / 2, marginTop: 5 }}
/>
</View>
)
}
/**
* 加载耗时操作
*/
componentDidMount() {
this.getDataFromFetch();
}
getDataFromFetch() {
fetch('http://gank.io/api/search/query/listview/category/福利/count/10/page/1')//请求地址
.then((response) => response.json())//取数据
.then((responseText) => {//处理数据
//通过setState()方法重新渲染界面
this.setState({
//改变加载ListView
load: true,
//设置数据源刷新界面
dataSource: this.state.dataSource.cloneWithRows(responseText.results),
})
})
.catch((error) => {
console.warn(error);
}).done();
}
}
module.exports = FetchG;
Post请求
fetch('https://mywebsite.com/endpoint/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstParam: 'yourValue',
secondParam: 'yourOtherValue',
})
})
这个博客将网络请求封装了一下可以参考下,你也就不必这么麻烦了