ListView.DataSource循环数据为React Native

时间:2015-12-14 09:47:17

标签: javascript reactjs react-native

当我做一个Console.log(this.state.dataSource)时,我得到如下图像,我现在得到“Row go here!”x 4,因为API返回4个结果。

我尝试检索用户数据,如电子邮件,但它不会“循环”并相应地打印。

我不确定这段代码是如何工作的,评论会有助于abit.Please Advice

enter image description here

    var messagesTab = React.createClass({
  componentWillMount: function() {
    fetch('https://randomuser.me/api/?results=4')
      .then(res => res.json())
      .then(res => this.updateDataSource(res));
  },
  getInitialState: function() {
    return {
      dataSource: new ListView.DataSource({
        rowHasChanged: (r1, r2) => r1 !== r2
      })
    };
  },
  updateDataSource: function(data){
    this.setState({
      dataSource: this.state.dataSource.cloneWithRows(data)
    })
  },
  renderRow: function (){
    return (
      <View>
        <Text>Row goes here!</Text>
      </View>
    );
  },
  render: function(){
    console.log(this.state.dataSource);
    return (
      <View style={ styleseact.container }>
        <ListView dataSource={ this.state.dataSource } renderRow={ this.renderRow } />
      </View>
    );
  }
});

enter image description here

当我执行console.log(数据)时,我得到了这个;在renderRow上

1 个答案:

答案 0 :(得分:3)

您正在覆盖您的DataSource声明。拆分声明并更新。

React.createClass之前声明:

var ds = new ListView.DataSource({
  rowHasChanged: (r1, r2) => r1 !== r2
});

getInitialState

中删除它
getInitialState: function() {
  return {
    dataSource: ds.cloneWithRows([])
  };
},

并在更新功能中引用它:

updateDataSource: function(data){
  this.setState({
    dataSource: ds.cloneWithRows(data)
  })
},