Reputation: 4853
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.
This ListView looks like this:
<ListView
dataSource={this.state.dataSource}
renderRow={this._renderStory}
onEndReached={this._getStories}
/>
The rowHasChanged
method looks like this.
this.state = {
dataSource: new ListView.DataSource({
rowHasChanged: (row1, row2) => {
return row1 !== row2;
},
}),
loaded: false,
};
All of that works just fine.
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),
});
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?
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.
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.
Upvotes: 5
Views: 9818
Reputation: 1918
<ListView
key={this._data}
dataSource={this.state.dataSource}
renderRow={this._renderStory}
onEndReached={this._getStories}
/>
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}
.
See ListView removing wrong row on dataSource update for more details.
Upvotes: 10
Reputation: 4033
In order for the list to update, you need to pass to it a duplicate of the array, not the same array. So in your case, something like this:
this.setState({
dataSource: state.dataSource.cloneWithRows(this._data.slice(0))
});
Upvotes: 2