我有一个iOS应用,我正在用react native制作.游戏类包含一个ListView组件.我在构造函数中设置状态,并包含一个dataSource
.我现在有一个硬编码的数据数组,存储在不同的州属性中(this.state.ds
).然后在componentDidMount
中,我使用cloneWithRows
方法克隆this.state.ds
作为视图的数据源.就ListView而言,这是相当标准的,而且运行良好.以下是代码:
/**
* Sample React Native App
* https://github.com/facebook/react-native
*/
'use strict';
var React = require("react-native");
var { StyleSheet, Text, View, ListView, TouchableHighlight } = React;
class Games extends React.Component {
constructor(props) {
super(props);
var ds = new ListView.DataSource({
rowHasChanged: (r1, r2) => r1 != r2
});
this.state = {
ds: [
{ AwayTeam: "TeamA", HomeTeam: "TeamB", Selection: "AwayTeam" },
{ AwayTeam: "TeamC", HomeTeam: "TeamD", Selection: "HomeTeam" }
],
dataSource: ds
};
}
componentDidMount() {
this.setState({
dataSource: this.state.dataSource.cloneWithRows(this.state.ds)
});
}
pressRow(rowData) {
var newDs = [];
newDs = this.state.ds;
newDs[0].Selection = newDs[0] == "AwayTeam" ? "HomeTeam" : "AwayTeam";
this.setState({
dataSource: this.state.dataSource.cloneWithRows(newDs)
});
}
renderRow(rowData) {
return (
<TouchableHighlight
onPress={() => this.pressRow(rowData)}
underlayColor="#ddd"
>
<View style={styles.row}>
<Text style={{ fontSize: 18 }}>
{rowData.AwayTeam} @ {rowData.HomeTeam}{" "}
</Text>
<View style={{ flex: 1 }}>
<Text style={styles.selectionText}>
{rowData[rowData.Selection]}
</Text>
</View>
</View>
</TouchableHighlight>
);
}
render() {
return (
<ListView
dataSource={this.state.dataSource}
renderRow={this.renderRow.bind(this)}
/>
);
}
}
var styles = StyleSheet.create({
row: {
flex: 1,
flexDirection: "row",
padding: 18,
borderBottomWidth: 1,
borderColor: "#d7d7d7"
},
selectionText: {
fontSize: 15,
paddingTop: 3,
color: "#b5b5b5",
textAlign: "right"
}
});
module.exports = Games
我遇到的问题来自pressRow
法.当用户按下该行时,我希望 Select 发生变化,并在设备上呈现变化.通过一些调试,我注意到,即使我正在更改newDs
数组中对象的Selection
属性,this.state.ds
中对象的相同属性也会更改,this.state.dataSource._dataBlob.s1
中的对象也会更改.通过进一步调试,我发现由于其他数组已经更改,ListView的DataSource对象无法识别更改,因为当我设置状态并调用rowHasChanged
时,它正在克隆的数组与数组this.state.dataSource._dataBlob.s1
匹配,因此它看起来不像更改,也不会重新加载.
有什么 idea 吗?