React Native ListView不显示数据

时间:2015-12-09 06:54:33

标签: listview dictionary react-native

我有一系列称为合作伙伴的词典。每个字典都有标题键和其他键。我希望用每个字典的标题填充ListView。

在我的ListView构造函数中,我有以下行。

    this.ds= new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2})
this.state = {
  dataSource: this.ds.cloneWithRows(this._partners()),
}

然后我的_partners函数看起来像这样

    _partners(){
  var dataBlob = []
  for (var ii = 0; ii < partners.length; ii++) {
    dataBlob.push(partners[ii].title);
  }
  return dataBlob;
}

ListView

中没有显示任何内容

但是,如果我将_partners代码更改为

    _partners(){
  var dataBlob = []
  for (var ii = 0; ii < partners.length; ii++) {
    dataBlob.push(partners[ii]);
  }
  return dataBlob;
}

然后ListView工作并由整个字典填充。

1 个答案:

答案 0 :(得分:0)

我认为问题可能是你对ds.cloneWithRows赋值的定义。我把它从构造函数中移出来作为React类定义之上的变量,它运行正常。有一个示例项目here,代码如下。

https://rnplay.org/apps/05ivvQ

'use strict';

var React = require('react-native');
var {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  ListView,
  TouchableHighlight
} = React;

var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2})
var partners = [{title: 'President', name: 'chris'}, {title: 'Manager', name: 'Melissa'}, {title: 'CEO', name: 'Amanda'}]

class SampleApp extends React.Component {

  constructor(props){
    super(props)
    this.state = {
        dataSource: ds.cloneWithRows(this._partners()),
    }
  }

  _partners(){
    var dataBlob = []
    for (var ii = 0; ii < partners.length; ii++) {
      dataBlob.push(partners[ii].title);
    }
    return dataBlob;
  }

  _renderRow(rowData) {
    return <TouchableHighlight underlayColor="ededed" style={{ height:60, backgroundColor: '#efefef', borderBottomWidth:1, borderBottomColor: '#ddd', flexDirection:'row', justifyContent: 'center', alignItems: 'center' }}>
        <Text style={{ fontSize:18 }}>{rowData}</Text>
      </TouchableHighlight>
  }

  render() {
    console.log('Partners: ', this._partners() )
    return (
      <View style={styles.container}>
        <ListView
         dataSource={this.state.dataSource}
         renderRow={ this._renderRow } />
      </View>
    );
  }
}

var styles = StyleSheet.create({
  container: {
    flex: 1,
    marginTop:60
  },

});

AppRegistry.registerComponent('SampleApp', () => SampleApp);