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

相关文章
相关标签/搜索