React Native 基础练习指北(二)
承接上文《React Native 基础练习指北(一)》,我们来看看React Native如果通过接口获取线上数据并展示。 Tips: 如果使用 一、展示单条数据通常我们会在 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赛季的相关信息(未经授权,悄悄的使用,打枪的不要)。 接下来,我们要添加一些初始化的状态,我们可以通过 getInitialState: function() { return { teams: null,}; }, 当 componentDidMount: function() { this.fetchData(); }, 下面,我们需要添加 fetchData: function() { fetch(REQUEST_URL) .then((response) => response.json()) .then((responseData) => { this.setState({ teams: responseData.result.data,}); }) .done(); }, 现在,我们需要修改 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模拟器中
二、展示数据列表下面我们来看看如何把所有数据展示在 首先我们在最上面定义 var { AppRegistry,Image,ListView,StyleSheet,Text,View } = React; 接下来,我修改 render: function() { if (!this.state.loaded) { return this.renderLoadingView(); } return ( <ListView dataSource={this.state.dataSource} renderRow={this.renderScoreboard} style={styles.listView} /> ); },
我们不难发现,我们使用了 getInitialState: function() { return { dataSource: new ListView.DataSource({ rowHasChanged: (row1,row2) => row1 !== row2,}),loaded: false,}; }, 下面是完善后的 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: { paddingTop: 20,backgroundColor: '#F5FCFF',},
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |