简体   繁体   中英

React Native ListView not showing data

I have an array of dictionories called partners. Each dictionary has a title key as well as other keys. I am looking to populate a ListView with the title of each dictionary.

In my ListView constructor I have the following line.

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

Then my _partners function looks like this

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

Nothing is showing in the ListView

However if I change the _partners code to

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

Then the ListView works and is populated by the entire dictionary.

I think the issue may be your definition of the ds.cloneWithRows assignment. I moved it out of the constructor to be a variable above the React class definition and it is working fine. There is a sample project here and the code is below.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM