ios - React native ListView 数据源设置(dataSource)

查看:97
本文介绍了ios - React native ListView 数据源设置(dataSource)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

我想从json解析数据后以listview的形式表现出来:

现在的问题是: 因为json取到的是一个结构体数组,里面有姓名,有编号,但是我并不能将取到的这个结构体数组设置成数据源,提示错误如下:

请问应该如何解决?

代码如下:(其中try1为设置listview的样式,只是之前做的试验,因为数据源没有设置成功所以还没有设置关联的数据)

import React, { Component } from 'react';
import { AppRegistry, ListView,StyleSheet,TouchableOpacity,Image,TouchableHighlight,center,Text, View } from 'react-native';

class ListViewBasics extends Component {
  // 初始化模拟数据
  constructor(props) {
    super(props);
    const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    this.state = {
      dataSource: ds.cloneWithRows(this.try2())
    };
  }
  try1(){
    return (<View style = {styles.cellRight}>
                <Text style={styles.celltext}>{'ss'}</Text>
             </View>
             );
  }
  try2(){
    fetch('http://v.6.cn/coop/iphone/index.php?padapi=coop-iphone-top.php')
    .then((response) => response.json())
    .then((jsondata) => {
//      console.log('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
//      console.log("用户名:"+jsondata.getwealth.d[0].username)
//      console.log("房号为:"+jsondata.getwealth.d[0].rid)

      return jsondata.getwealth.d;
    })
  }

  render() {
    return (
      <View style={{paddingTop: 22}}>
        <ListView
          dataSource={this.state.dataSource}
          renderRow={(rowData1) => this.try1()}
        />
      </View>
    );
  }
}

解决方案

转:
fetch是异步函数,你可以理解为它不能有返回值。举个例子,你去邮局寄信,你不会投完信后就站在那里等回信,那是不可能等到的。
简而言之,不能在then中返回,只能在then中继续setState,把返回的数据放在state中。那么收到回信之前怎么办——你必须设定一个空的state初始值,或者render一个loading视图。

这篇关于ios - React native ListView 数据源设置(dataSource)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆