这次讲的是如何从网上获取数据,并显示出来
首先将获取对象的URL放在最上面
var REQUEST_URL = 'https://raw.githubusercontent.com/facebook/react-native/master/docs/MoviesExample.json';
初始化数据
constructor(props) {
super(props);
this.state = {
movies: null,
};
}
获取数据,这个是componentDidMount是在进入状态,也就是初始化完后执行一次
componentDidMount() {
this.fetchData();
}
fetchData() {
fetch(REQUEST_URL)
.then((response) => response.json())
.then((responseData) => {
this.setState({
movies: responseData.movies,
});
})
.done();
}
通过判断是否成功获取数据,对不同情况显示不同的布局
render() {
if (!this.state.movies) {
return this.renderLoadingView();
}
var movie = this.state.movies[0];
return this.renderMovie(movie);
}
renderLoadingView() {
return (
<View style={styles.container}>
<Text>
Loading movies...
Text>
View>
);
}
renderMovie(movie) {
return (
<View style={styles.container}>
<Image
source={{uri: movie.posters.thumbnail}}
style={styles.thumbnail}
/>
<View style={styles.rightContainer}>
<Text style={styles.title}>{movie.title}Text>
<Text style={styles.year}>{movie.year}Text>
View>
View>
);
}
完整代码如下
/**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
var MOCKED_MOVIES_DATA = [
{title: 'Title', year: '2015', posters: {thumbnail: 'http://img5.imgtn.bdimg.com/it/u=4080105893,4096129906&fm=206&gp=0.jpg/'}},
];
var REQUEST_URL = 'https://raw.githubusercontent.com/facebook/react-native/master/docs/MoviesExample.json';
import React, { Component } from 'react';
import {
AppRegistry,
Image,
StyleSheet,
Text,
View,
ListView,
} from 'react-native';
export default class MyProject extends Component {
constructor(props) {
super(props);
this.state = {
movies: null,
};
}
componentDidMount(){
this.fetchData();
}
fetchData() {
fetch(REQUEST_URL)
.then((response) => response.json())
.then((responseData) => {
this.setState({
movies: responseData.movies,
});
})
.done();
}
render() {
if (!this.state.movies) {
return this.renderLoadingView();
}
var movie = this.state.movies[0];
return this.renderMovie(movie);
}
renderLoadingView()
{
return (
Loading movies...
);
}
renderMovie(movie) {
return (
{movie.title}
{movie.year}
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
thumbnail: {
width: 53,
height: 81,
marginLeft:30,
},
rightContainer: {
flex: 1,
},
title: {
fontSize: 20,
marginBottom: 8,
textAlign: 'center',
},
year: {
textAlign: 'center',
},
listView: {
paddingTop: 20,
backgroundColor: '#F5FCFF',
},
});
AppRegistry.registerComponent('MyProject', () => MyProject);
再见