我不确定为什么在我的数据发生变化时ListView没有更新.我已经将代码条带化,以便于阅读和创建一个rnplay:
https://rnplay.org/apps/ivG0mg
我期望发生的是,用户单击列表项并且行的bool isCollapsed切换为使背景变为红色.实际发生的是数据源已更新但列表视图无法识别更改并且未呈现任何新内容.有任何想法吗?
'use strict'; var React = require('react-native'); var { ScrollView,Text,Image,StyleSheet,TouchableHighlight,AppRegistry,View,ListView,} = React; var styles = StyleSheet.create({ container: { flex: 1,flexDirection: 'column',padding: 15,},red: { backgroundColor: "red",} }); var foods = [ {key: 'Almond Milk (Homemade)',details:''},{key: 'Club Soda',details:'',isCollapsed: true},{key: 'Coconut Milk/Cream',{key: 'Coconut Water',{key: 'Coffee/Espresso',{key: 'Fruit Juice',{key: 'Kombucha',{key: 'Mineral Water',{key: 'Unsweetened Tea',{key: 'Water',]; class SampleApp extends React.Component{ constructor(props){ super(props); var ds = new ListView.DataSource({ rowHasChanged: (row1,row2) => row1 !== row2,}); this.state = { dataSource: ds.cloneWithRows(foods),}; } _renderRow(data,sectionID,rowID) { return ( <TouchableHighlight style={[ styles.container,data.isCollapsed && styles.red]} onPress={()=>this.onCollapse(rowID)}> <Text>{data.key}</Text> </TouchableHighlight> ); } onCollapse(rowID: number) { console.log("rowID",rowID); foods[rowID].isCollapsed = !foods[rowID].isCollapsed; this.setState({dataSource: this.state.dataSource.cloneWithRows(foods)}); } render() { return( <ListView style={styles.subContainer} dataSource={this.state.dataSource} renderRow={this._renderRow.bind(this)} initialListSize={15}/> ) } }; AppRegistry.registerComponent('SampleApp',() => SampleApp);
这是一个工作版本的链接:
https://rnplay.org/apps/GWoFWg
这些是我需要做的修改来修复它:
constructor(props){ super(props); var ds = new ListView.DataSource({ rowHasChanged: (row1,}); this.state = { dataSource: ds.cloneWithRows(foods),db: foods,}; }
和这个:
onCollapse(rowID: number) { var newArray = this.state.db.slice(); newArray[rowID] = { key: newArray[rowID].key,details: newArray[rowID].details,isCollapsed: newArray[rowID].isCollapsed == false ? true : false,}; this.setState({ dataSource: this.state.dataSource.cloneWithRows(newArray),db: newArray,}); }