React native fetch json 显示在ListView
发布时间:2020-12-15 06:29:08 所属栏目:百科 来源:网络整理
导读:1.构造函数设置data为空 constructor(props){ super(props); this.state = { data: null } } 2.fetch 数据把data设置为ListView.DataSource componentDidMount(){ fetch('http://127.0.0.1/getScore/100') .then((response)=response.json()) .then((jsondat
1.构造函数设置data为空constructor(props){ super(props); this.state = { data: null } } 2.fetch 数据把data设置为ListView.DataSourcecomponentDidMount(){ fetch('http://127.0.0.1/getScore/100') .then((response)=>response.json()) .then((jsondata)=>{ this.setState({ data: new ListView.DataSource({rowHasChanged:(r1,r2) => r1 != r2}).cloneWithRows(jsondata.data),}); }) .catch((error)=>{ alert(error); }); } rowHasChanged(prevRowData,nextRowData):指定我们更新row的策略,一般来说都是prevRowData和nextRowData不相等时更新row cloneWithRows(dataBlob,rowIdentities): 该方法接收两个参数,dataBlob是原始数据源。在没有section的时候使用此方法,传入一个数组。rowIdentities为可选类型,为数据源的每一项指明一个id。默认的id为字符串'0','1','2'...dataBlob.count。 3. render ListViewrender() { if(!this.state.data){ return( <Text>Loading... </Text> ) }else{ return( <ListView dataSource={this.state.data} renderRow={(rowData)=>this.renderRow(rowData)} > </ListView> ); } } 指定了ListView的dataSource和如何renderRow 4. RenderRowrenderRow(rowData){ return( <View style={styles.lvRow}> <Image style={styles.img} source = { { uri: rowData.headimgurl } }/> <View style = { styles.textView }> <Text style = { styles.textTitle } numberOfLines = { 1 }> { rowData.nickname } </Text> <Text style = { styles.textContent }> { rowData.score } </Text> </View> </View> ) } 5. Style设置const styles = StyleSheet.create({ lvRow:{ flex:1,flexDirection:'row',padding:10,},textView: { flex: 1,justifyContent: 'center',alignItems: 'center',padding: 5,textTitle: { flex: 1,textAlign: 'center',color: '#f00',textContent: { flex: 1,fontSize: 11,color: '#000',img:{ height:100,width:100,}); 6. 最终效果React-Native (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |