I was trying to figure out how I was able to create a ListView that can often get new data and push it to the fore. In the code below, the list does not reflect the correct change, instead of having a new line at the top, the last is duplicated.
'use strict'; var React = require('react-native'); var { AppRegistry, StyleSheet, Text, View, ListView, TouchableHighlight, } = React; var listview = React.createClass({ rows: [], _rowHasChanged: function (r1, r2) { // if (r1 !== r2) // console.log('rowChanged', r1, r2); // else // console.log('row didn\'t Changed', r1, r2); return r1 !== r2; }, getInitialState: function() { return { dataSource: new ListView.DataSource({rowHasChanged: this._rowHasChanged}), }; }, componentDidMount: function () { this.rows = [ {id: 0, text: '0: text'}, {id: 1, text: '1: text'}, {id: 2, text: '2: text'}, {id: 3, text: '3: text'}, ]; this.setState({ dataSource: this.state.dataSource.cloneWithRows(this.rows), }); }, pushTopRow: function () { var id = this.rows.length; this.rows.unshift({id: id, text: id + ': text'}); this.setState({ dataSource: this.state.dataSource.cloneWithRows(this.rows), }); }, render: function() { return ( <View style={styles.container}> <ListView dataSource={this.state.dataSource} renderRow={(rowData) => <Text key={rowData.id}>{rowData.text}</Text>} /> <TouchableHighlight onPress={this.pushTopRow}> <Text>PUSH TOP</Text> </TouchableHighlight> </View> ); }, }); var styles = StyleSheet.create({ container: { flex: 1, backgroundColor: 'orange', }, }); AppRegistry.registerComponent('listview', () => listview);
then I tried:
pushTopRow: function () { var id = this.rows.length; var newRow = [{id: id, text: id + ': text'}]; this.rows = newRow.concat(this.rows); this.setState({ dataSource: this.state.dataSource.cloneWithRows(this.rows), }); },
this really works, but I do not understand why the first method does not work. I am trying to figure out what works best with ListView:
- Should I use cloneWithRows with the new array anyway, even for a single add / delete operation?
- Is there anything else to set the ListView / DataSource mechanism to work correctly with minimal redrawing (keys, hasRowChanged specific comparison?),
kind of flaw in the documents and examples, it would be great to clarify this for me and for everyone. Thank you and you have a nice day of code.