【问题标题】:Deleting a ListView item in React Native在 React Native 中删除 ListView 项
【发布时间】:2017-03-19 22:08:05
【问题描述】:

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

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 个小时来解决这个问题,我很确定我做的一切都是正确的。

【问题讨论】:

    标签: listview react-native react-native-listview


    【解决方案1】:

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

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

    newList 将包含已删除的项目,但实际上我们需要的是删除项目后的新列表。

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

    不要将items 存储在状态对象中。而是将其存储为类实例变量并设置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)
        });
    }
    

    【讨论】:

    • 谢谢!解决了我的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-06
    • 2020-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多