加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

react native 学习笔记----网络

发布时间:2020-12-15 08:27:13 所属栏目:百科 来源:网络整理
导读:原链接为http://blog.csdn.net/wxq888/article/details/52388990#comments。下面为原文内容。 React Native提供了和web标准一致的 Fetch API ,用于满足开发者访问网络的需求。 发起网络请求 要从任意地址获取内容的话,只需简单地将网址作为参数传递给fetch

原链接为http://blog.csdn.net/wxq888/article/details/52388990#comments。下面为原文内容。


React Native提供了和web标准一致的Fetch API,用于满足开发者访问网络的需求。

发起网络请求

要从任意地址获取内容的话,只需简单地将网址作为参数传递给fetch方法即可:

fetch('https://mywebsite.com/mydata.json')
废话不多说,给个例子大家看看,详细看代码中的注释,

import React,{ Component } from 'react';
import { AppRegistry, Image,ListView, StyleSheet, Text, View } from 'react-native';

var REQUEST_URL = 'https://raw.githubusercontent.com/facebook/react-native/master/docs/MoviesExample.json';

class HttpTest extends Component {
constructor(props) {
super(props); //这一句不能省略,照抄即可
this.state = {
movies: null,//这里放你自己定义的state变量及初始值
};
// 在ES6中,如果在自定义的函数里使用了this关键字,则需要对其进行“绑定”操作,否则this的指向不对
// 像下面这行代码一样,在constructor中使用bind是其中一种做法(还有一些其他做法,如使用箭头函数等)

this.fetchData = this.fetchData.bind(this);
}

render() {
if (!this.state.movies) {
return this.renderLoadingView(); //刚开始网络数据没有拉取下来,先展示一个加载页面
}

var movie = this.state.movies[0];
return this.renderMovie(movie);
}

fetchData() {
fetch(REQUEST_URL)
.then((response) => response.json())
.then((responseData) => {
// 注意,这里使用了this关键字,为了保证this在调用时仍然指向当前组件,我们需要对其进行“绑定”操作
this.setState({ //调用setState,会触发调用render,重新渲染界面
movies: responseData.movies,
});
})
.done();
}

componentDidMount() {//React组件的一个生命周期方法,组件加载完后调用。
this.fetchData();
}

renderLoadingView() {
return (
<View style={styles.container}>
<Text>
正在加载电影数据……
</Text>
</View>
);
}

renderMovie(movie){
return (
<View style={styles.container}>
<Image source={{uri:movie.posters.thumbnail}}
style={styles.thumbnail}></Image>
<View style={styles.rightContainer}>
<Text style={styles.title}>{movie.title}</Text>
<Text style={styles.year}>{movie.year} </Text>
</View>
</View>
);
}
}

const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection:'row',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
thumbnail: {
width: 53,
height: 80,
rightContainer:{
flex:1,
title:{
fontSize:20,
marginBottom:8,
textAlign:'center',
year:{
textAlign:'center',

});


AppRegistry.registerComponent('HttpTest',() => HttpTest);

运行结果:



本例子节选于:react native综合小例子:“电影列表”。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读