我正在使用react-native开发一个iOS应用程序。Game类包含一个ListView组件。我在构造函数中设置状态并包括一个dataSource
。目前,我有一个硬编码的数据数组,存储在不同的状态属性(this.state.ds
)中。然后,在componentDidMount
中,我使用cloneWithRows
方法将this.state.ds
克隆为视图的dataSource
。这在ListViews方面是相当标准的,并且工作得很好。以下是代码:
/**
* 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`方法中。当用户按下行时,我希望选择项更改并在设备上呈现更改。通过一些调试,我发现尽管我正在更改`newDs`数组中对象的`Selection`属性,但是`this.state.ds`和`this.state.dataSource._dataBlob.s1`中的对象的相同属性也会发生变化。经过进一步的调试,我发现由于那些其他数组已经改变,ListView的DataSource对象无法识别变化,因为当我设置状态并调用`rowHasChanged`时,它克隆的数组与`this.state.dataSource._dataBlob.s1`数组匹配,因此看起来没有任何变化,不会重新渲染。
有什么想法吗?
var copy = Object.assign({}, obj);
来实现对象的复制,而不是手动重建整个对象。 - Eric GnewRows[rowId] = { ...this._sampleData[rowId], favorited: rowData.favorited ? false : true }
的意思是将_sampleData
中rowId
对应的数据复制到newRows[rowId]
,并将该行的favorited
值取反。如果原来为true
则变为false
,如果原来为false
则变为true
。 - Eric G