您的位置:首页 > 理论基础 > 计算机网络

ReactNative学习实例(三) 使用fetch获取网络数据

2017-03-01 14:53 375 查看
实例来自http://blog.csdn.net/u014360817/article/details/52447516

RN自带了一个非常优雅的网络操作库fetch,下面的这个例子从gankio的接口拿到了美女图片的url然后通过state 传给列表组件,列表里返回图片组件显示图片。网络数据获取方法写在componentDidMount中,这个方法是组件生命周期中需要调用的一个方法。

class AwesomeProject extends Component {// 初始化模拟数据

constructor(props) {
super(props);

const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => {r1 !== r2}});
this.state = {
dataSource: ds,
load:false,
text:''
};
}

//耗时操作放在这里面
componentDidMount(){
this.getNet();
}

getNet(){
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();
}

render() {
if(this.state.load){
return (
<View style={{flex: 1, paddingTop: 22}}>
<ListView
dataSource={this.state.dataSource}
renderRow={(rowData)=>
<View>
<Image
style={{ width: 400, height: 250, marginTop: 5 }}
source={{uri:rowData.url}}/>
</View>}
/>
</View>
);
} else{
return(
<View>
<Text>loading......</Text>
</View>
);
}
}
}

这里使用的是fetch的一个参数的方法,参数自然就是url,默认请求方式是GET,还有两个参数的方法,第二个参数是一组请求参数。执行fetch后返回一个Promise对象,通过then继续获取数据,这里response.json表示获取json格式的数据,也可以用text获取纯文本的数据。
获取到json后接下来就是解析json,这里的json里面有一个result数组,直接拿出来作为数据源的数据传入即可。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: