我创建了一个使用 ListView
的组件以显示联系人列表。单击一行时,我会更新 state
中的数组的组件,包含所有选定的联系人。但是,我没有将此数组用作 dataSource
我的 ListView
成分。
我想重绘ListView
每次修改此数组以显示所选联系人的图像时。
这是我目前情况的一个例子:
renderListView: function(){
<ListView
dataSource={this.state.dataSource}
renderRow={this.renderRow}
style={styles.listView}
/>
}
renderRow:function(row){
return if(this.state.something === true) <Text>Something</Text>
else <Text>Something Else</Text>
}
我试着打电话
.forceUpdate()
,它调用 render
方法而不是 renderRow
方法。有什么建议吗?
最佳答案
我刚刚遇到了同样的问题。在这里查看我的问题:React Native ListView not updating on data change
基本上,ListView 组件似乎存在一个错误,您需要重建数据源中更改的每个项目,以便 ListView 重新绘制它。
这是一个工作示例:
https://rnplay.org/apps/GWoFWg
首先,创建数据源和数组的副本并将它们保存到状态。就我而言,foods
是数组。
constructor(props){
super(props);
var ds = new ListView.DataSource({
rowHasChanged: (row1, row2) => row1 !== row2,
});
this.state = {
dataSource: ds.cloneWithRows(foods),
db: foods,
};
}
当您想要更改数据源中的某些内容时,请复制您保存到状态的数组,使用更改重建项目,然后将更改后的新数组保存回状态(db 和数据源)。
onCollapse(rowID: number) {
console.log("rowID", rowID);
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,
});
}
关于listview - 当 this.state 改变(但不是数据源)时如何强制重绘 ListView。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33436902/