承接上文《React Native 基礎練習指北(一)》,咱們來看看React Native若是經過接口獲取線上數據並展現。react
Tips: 若是使用cmd+R
沒法刷新效果,請檢查index.ios.js
的權限設置。ios
一般咱們會在require('react-native');
後,寫好儲存API的變量(此處咱們使用簡單的API作演示):json
var REQUEST_URL = 'http://platform.sina.com.cn/sports_all/client_api?app_key=3571367214&_sport_t_=football&_sport_s_=opta&_sport_a_=teamOrder&type=213&season=2015&format=json';
這裏咱們暫時使用新浪體育2015年中超聯賽信息的接口,能夠獲得中超16支球隊2015賽季的相關信息(未經受權,悄悄的使用,打槍的不要)。segmentfault
接下來,咱們要添加一些初始化的狀態,咱們能夠經過this.state.movies === null
判斷數據是否已經成功加載。將下面的代碼加在render
方法前面:react-native
getInitialState: function() { return { teams: null, }; },
當react-native
組件加載完成後,咱們須要發送咱們的請求。React會在react-native
組件加載完成後,使用componentDidMount
方法發送請求,而且只發送一次。api
componentDidMount: function() { this.fetchData(); },
下面,咱們須要添加fetchData
方法,它是用來取回數據的。在React的工做流程中,setState
會觸發一次重繪,隨後render
方法會發現this.state.movies
再也不是null
,你所須要作的就是使用this.setState({movies: data})
。牢記在最後要使用done()
,不然不會出現錯誤提示。app
fetchData: function() { fetch(REQUEST_URL) .then((response) => response.json()) .then((responseData) => { this.setState({ teams: responseData.result.data, }); }) .done(); },
如今,咱們須要修改render
方法,從而當咱們沒有拿到數據時,渲染出一個loading
視圖,隨後呈現出第一個球隊信息。fetch
render: function() { if (!this.state.teams) { return this.renderLoadingView(); } var team = this.state.teams[11]; return this.renderTeam(team); }, renderLoadingView: function() { return ( <View style={styles.container}> <Text> Loading teams... </Text> </View> ); }, renderTeam: function(team) { return ( <View style={styles.container}> <Image source={{uri: team.logo}} style={styles.thumbnail} /> <View style={styles.rightContainer}> <Text style={styles.name}>{team.team_cn}</Text> <Text style={styles.rank}>{team.team_order}</Text> </View> </View> ); }
如今,在iOS模擬器中cmd+R
,在請求拿到返回數據以前,你會看到「Loading teams...」,隨後會渲染出第一個球隊信息。ui
下面咱們來看看如何把全部數據展現在ListView
組件中,而不是僅僅展現一條數據。this
首先咱們在最上面定義React
的時候加入ListView
:
var { AppRegistry, Image, ListView, StyleSheet, Text, View } = React;
接下來,我修改render
方法,從而可以以列表方式展現出數據:
render: function() { if (!this.state.loaded) { return this.renderLoadingView(); } return ( <ListView dataSource={this.state.dataSource} renderRow={this.renderScoreboard} style={styles.listView} /> ); },
ListView
能夠判斷哪些數據發生了改變,並在數據更新時,體如今列表中。
咱們不難發現,咱們使用了this.state
中的dataSource
。下一步在getInitialState
返回的對象中添加空的dataSource
。隨後,咱們講數據存到dataSource
中,我再也不使用this.state.movies
來避免數據重複加載,而是使用布爾值this.state.loaded
來判斷數據是否成功獲取。
getInitialState: function() { return { dataSource: new ListView.DataSource({ rowHasChanged: (row1, row2) => row1 !== row2, }), loaded: false, }; },
下面是完善後的fetchData
方法:
fetchData: function() { fetch(REQUEST_URL) .then((response) => response.json()) .then((responseData) => { this.setState({ dataSource: this.state.dataSource.cloneWithRows(responseData.result.data), loaded: true, }); }) .done(); },
最後,咱們把ListView
的樣式添加到styles
對象中:
listView: { paddingTop: 20, backgroundColor: '#F5FCFF', },