React Native 基礎練習指北(二)

承接上文《React Native 基礎練習指北(一)》,咱們來看看React Native若是經過接口獲取線上數據並展現。react

Tips: 若是使用cmd+R沒法刷新效果,請檢查index.ios.js的權限設置。ios

1、展現單條數據

一般咱們會在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

demo-1

2、展現數據列表

下面咱們來看看如何把全部數據展現在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',
},

demo-2

相關文章
相關標籤/搜索