在 React Native 中删除 ListView 项

Deleting a ListView item in React Native

我很难从 ListView 中删除一行。它删除列表的最后一个元素,无论单击哪个元素。 然而,console.log 告诉我数组已正确删除项目,但呈现错误... 互联网上已有一些解决方案,但 none 帮我解决了我的问题。

GIF of my problem

日志

如您所见,它确实删除了正确的项目,但显示了错误的数组?

Nov 6 22:18:39 Viviennes-Air reminders[25992] <Notice>: { rowID: '0' } Nov 6 22:18:39 Viviennes-Air reminders[25992] <Notice>: [ 'testing 2', 'testing 3' ] Nov 6 22:18:39 Viviennes-Air reminders[25992] <Notice>: { _rowHasChanged: [Function: rowHasChanged], _getRowData: [Function: defaultGetRowData], _sectionHeaderHasChanged: [Function], _getSectionHeaderData: [Function: defaultGetSectionHeaderData], _dataBlob: { s1: [ 'testing 2', 'testing 3' ] }, _dirtyRows: [ [ false, false, true ] ], _dirtySections: [ false ], _cachedRowCount: 3, rowIdentities: [ [ '0', '1', '2' ] ], sectionIdentities: [ 's1' ] }

这是我的构造函数:

constructor(props) {
super(props);
const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.state = {
  items: [],
  dataSource: ds.cloneWithRows([]),
  newItem: "",
};}

列表视图:

<ListView
        style={styles.container}
        dataSource={this.state.dataSource}
        enableEmptySections={true}
        renderRow={(data, sectionID, rowID) => this.renderRow(data, sectionID, rowID)}
        renderSeparator={(sectionId, rowId) => <View key={rowId} style={styles.separator}/>}
      />

renderRow 函数:

renderRow(data, sectionID, rowID){
console.log("ITEM: ", data)
return <TouchableOpacity style={styles.listItem} onPress={() => this._delete({rowID})}
            activeOpacity={0.1}>
            <Text style={styles.listItemText}>{data}</Text>
            </TouchableOpacity>}

最后,删除函数:

_delete(index){
  this.state.items.splice(index, 1)
  console.log(index)
  console.log(this.state.items)
  this.setState({
    dataSource: this.state.dataSource.cloneWithRows(this.state.items)
  })
  console.log(this.state.dataSource)}

我已经花了 2 个小时试图解决这个问题,我很确定我做的一切都是正确的。

我同意 Burak Karasoy 的观点,但是代码中还有一个错误。

var newList= this.state.items.splice(index, 1)

newList会包含被删除的item,但实际上我们需要的是删除item后的新List。

因此,使您的代码正常工作所需的更改是,

不要将 items 存储在状态对象中。而是将其存储为 class 实例变量并设置 dataSource,如下面的代码

this.items=this.getItems();
this.setState({
        dataSource: this.state.dataSource.cloneWithRows(this.items)
 });

现在更新您的 _delete 方法,如下所示

_delete(index) {
    this.items.splice(index, 1)// This will remove the element at index, and update this.items with new array
    this.setState({
      dataSource: this.state.dataSource.cloneWithRows(this.items)
    });
}