'use strict';
import React, {
AppRegistry,
Component,
StyleSheet,
Text,
View,
Image,
ToastAndroid,
} from 'react-native';
var REQUEST_URL = 'https://raw.githubusercontent.com/facebook/react-native/master/docs/MoviesExample.json';
class AwesomeProject extends Component {
//返回當前顯示的view
render() {
// ToastAndroid.show(JSON.stringify(this.state.movies),ToastAndroid.SHORT)
//由于剛開始的的時候設置movies的職位空,所以第一次會加載等待的view
if (!this.state.movies) {
return this.renderLoadingView();
}
//只獲取第一個數組的數據
var movie = this.state.movies[0];
return this.renderMovie(movie);
}
//加載等待的view
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>
);
}
//js組件的構造函數,js的生命周期
constructor(props) {
super(props);
//state內部維護的一個狀態,我們剛開始進來的為空,來加載空的view
this.state = {
movies: null,
};
}
//rn的生命周期,初始化的時候會執行
componentDidMount() {
//去拉取電影的接口的數據
this.fetchData();
}
fetchData() {
//這個是js的訪問網絡的方法
fetch(REQUEST_URL)
//ES6的寫法左邊代表輸入的參數右邊是邏輯處理和返回結果
.then((response) => response.json())
.then((responseData) => {
this.setState({
movies: responseData.movies,
});
})
.done();
}
}
const styles = StyleSheet.create({
title: {
fontSize: 20,
marginBottom: 8,
textAlign: 'center',
},
year: {
textAlign: 'center',
},
container: {
flex: 1,
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
rightContainer: {
flex: 1,
},
thumbnail: {
width: 53,
height: 81,
},
});
AppRegistry.registerComponent('AwesomeProject', () => AwesomeProject);
React Native學習筆記加載網絡上數據顯示出來
最后編輯于 :
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
推薦閱讀更多精彩內容
- 使用ListView加載網絡數據 本文采用fecth來進行網絡請求的 創建一個構造器 創建網絡請求 創建Loadi...
- React-Native 學習筆記 - 使用FlastList加載網絡數據 聲明變量 網絡請求方法 加載等待的Vi...