我有一个呈现为视图的数据,并且遇到了有关如何删除已刷过的特定索引的问题
我使用FlatList的方式如下
render() {
this.leftOpenValue = Dimensions.get('window').width;
this.rightOpenValue = -Dimensions.get('window').width;
return (
<FlatList
data = {data}
keyExtractor = {data => data.id}
renderItem={ ({item}) => (
<View style={styles.container}>
<SwipeView
disableSwipeToRight = {false}
renderVisibleContent={() =>
<View>
<Text style={styles.text}> {item.title} </Text> // This repeats 9 times (9 Index)
</View>
}
renderRightView={() => (
<View style={{flex:1, justifyContent: 'flex-end', alignItems: 'center', backgroundColor: 'red'}}>
</View>
)}
leftOpenValue = {this.leftOpenValue}
rightOpenValue = {this.rightOpenValue}
onSwipedLeft={() => alert("deleted")}
swipeDuration = {300}
swipeToOpenPercent = {40}
disableSwipeToRight = {true}
/>
</View>
)}
/>
);
我已经使用Swipeview进行滑动(react-native-swipeview)并删除了平面列表中的索引
我对如何从flatList中删除项目有疑问
答案 0 :(得分:6)
deleteItemById = id => {
const filteredData = this.state.data.filter(item => item.id !== id);
this.setState({ data: filteredData });
}
render() {
...
return (
<FlatList
data = {data} // Assuming this is `this.state.data`
keyExtractor = {({item}) => item.id}
renderItem={({item}) => (
<View style={styles.container}>
<SwipeView
...
onSwipedLeft={() => this.deleteItemById(item.id)}
...
/>
</View>
)}
/>
);
}
答案 1 :(得分:2)
将该项的ID传递到onSwipeLeft={this.deleteItem(item.id)}
并使用setState更新数据。
state = {
data: [{
title: 'Hello world',
id: 'hello'
},{
title: 'World says hello',
id: 'say'
}]
}
deleteItem = (id) => {
this.setState({
data: this.state.data.filter(item => item.id !== id)
})
}
答案 2 :(得分:0)
做一个普通的对象删除然后过滤你的状态来清理它
let _rem = this.state.data;
delete _rem[index_no];
this.setState({data: this.state.data.filter(args=>args!==index_no)});