反应原生:从 ListView 中删除项目 [英] React native: remove item from ListView

查看:33
本文介绍了反应原生:从 ListView 中删除项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Android 上使用 React Native (0.12.0) 并且在我的页面上有一个 ListView 组件.我希望能够从列表中删除项目.

I'm using React Native (0.12.0) on Android and have a ListView component on my page. I want to be able to remove items from the list.

这个 ListView 看起来像这样:

This ListView looks like this:

<ListView
    dataSource={this.state.dataSource}
    renderRow={this._renderStory}
    onEndReached={this._getStories}
    />

rowHasChanged 方法如下所示.

this.state = {
    dataSource: new ListView.DataSource({
        rowHasChanged: (row1, row2) => {
            return row1 !== row2;
        },
    }),
    loaded: false,
};

所有这些都很好.

现在,要删除一个项目,我有这个代码:

Now, to remove an item I have this code:

var indexOfItem = this._data.findIndex((item) => item.id === story.id);
this._data.splice(indexOfItem, 1);

this.setState({
    dataSource: this.state.dataSource.cloneWithRows(this._data),
});

我可以确认该项目正在从 this._data 中删除.this.state.dataSource._cachedRowCount 按原样减一.正在更新状态并触发渲染周期.但该项目不会从页面中删除.更重要的是,如果我在 this._renderStory() 中放入一个控制台日志,唯一发生的事情就是它在列表底部呈现一个 new 行.

I can confirm that the item is being removed from this._data. this.state.dataSource._cachedRowCount is reduced by one as it should be. The state is being updated and a render cycle triggered. But the item isn't removed from the page. What's more, if I put a console log in this._renderStory(), the only thing happening is it renders a new row at the bottom of the list.

我错过了什么吗?我还需要做其他步骤吗?

Am I missing something? Is there another step I need to do?

这里有人问了一个类似的问题,但他从来没有得到关于删除一行的答案.如何在 ListView 中添加/删除项目?

A similar question was asked here but he never got an answer about removing a row. How to add/Delete item into ListView?

我在这个地方看到的所有其他示例都没有删除项目的示例.

All the other examples I've seen around the place lack an example of removing an item.

更新:谢谢,它需要传递数组的克隆并设置一个键(抱歉只能接受一个答案).但这意味着正在呈现整个列表.最后,我只是在项目上设置了一个 'removed' 属性,测试了该属性的变化,如果一个项目被标记为删除,则在渲染方法中返回 null,这比重新渲染所有项目要快.

UPDATE: Thanks, it required passing a clone of the array AND setting a key (sorry can only accept one answer). But this meant the whole list was being rendered. In the end I just set a 'removed' property on the items, tested for that property changing and returned null in the render method if an item was flagged as remove, this was faster than re-rendering all items.

推荐答案

<ListView
  key={this._data}
  dataSource={this.state.dataSource}
  renderRow={this._renderStory}
  onEndReached={this._getStories}
/>

this._data设置ListView的key.如果您有一个 Key/ID 行数组,请像 key={this._data.IDArray} 一样使用它.

Set the key of the ListView with this._data. If you have an Key/ID array of rows, use it like key={this._data.IDArray}.

请参阅ListView 在数据源更新时删除错误行 了解更多详情.

See ListView removing wrong row on dataSource update for more details.

这篇关于反应原生:从 ListView 中删除项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆