javascript - 如何通过单击状态从 FlatList 中一一删除项目
问题描述
我在 FlatList 中创建了一个简单列表,项目已从名为data
. 我想通过单击每个项目来逐个删除项目,但我的问题是,当我单击一个项目时,所有项目都会同时被删除。
我怎样才能解决这个问题?
这看起来像我的应用程序:
这是代码:
const FoodList = () => {
const data = [
{ text: 'test1', backgroundColor: 'teal' },
{ text: 'test2', backgroundColor: 'teal' },
{ text: 'test3', backgroundColor: 'teal' },
{ text: 'test4', backgroundColor: 'teal' },
{ text: 'test5', backgroundColor: 'teal' },
{ text: 'test6', backgroundColor: 'teal' },
{ text: 'test7', backgroundColor: 'teal' },
{ text: 'test8', backgroundColor: 'teal' },
{ text: 'test9', backgroundColor: 'teal' },
{ text: 'test10', backgroundColor: 'teal' },
{ text: 'test11', backgroundColor: 'teal' },
]
let [itemState, setitemState] = useState(data);
return (
<View style={styles.container}>
<FlatList
data={itemState}
keyExtractor={(item, index) => index}
renderItem={({ item, index }) => (
<TouchableOpacity
style={[
{ flexDirection: 'row' }, { width: '100%' }, { alignItems: 'center' }, { flex: 1 }, { justifyContent: 'space-between' },
{ backgroundColor: item.backgroundColor }, { marginBottom: 10 }
]}
activeOpacity={0.7}
onPress={() => {
let removeItem = itemState.map((_item, _Index) => _Index !== index);
setitemState(itemState = removeItem);
}}
>
<Text style={{ fontSize: 30, color: 'white' }} >{item.text}{item.name}</Text>
<Icon type='FontAwesome5' name='trash-alt' style={{ color: 'white' }} />
</TouchableOpacity>
)}
/>
</View>
)
}
解决方案
问题在于您用于删除项目的功能。
map() 方法使用为每个数组元素调用函数的结果创建一个新数组。
filter() 方法创建一个数组,其中填充了所有通过测试的数组元素。
所以当你运行map((_item, _Index) => _Index !== index)
你的removeItem
意志是:
[false, false, false, true, false, false, false, false, false, false, false]
一堆布尔值没有明显呈现:)
为了删除项目使用filter((_item, _Index) => _Index !== index)
推荐阅读
- javascript - read() 后如何在 KendoGrid 中捕获 html 操作的结束?
- angular - 如何使用 Quill 和 Angular 添加自定义格式按钮?
- java - 如何从车速表应用程序中找到高速?
- c++ - 传递 std::vector
到外部函数 - javascript - 是什么让 Google Places API 无法在我的 C# 应用程序上自动完成?
- java - ItemWriter 只提交第一个提交间隔
- amazon-web-services - 使用 check/dry-run 开发 AWS 基础设施配置 ansible playbook
- vscode-settings - 在终端中更改 VSCode 错误字体颜色
- javascript - JavaScript 不适用于所有 HTML 页面
- javascript - 在每个循环中使用 setAttributeNS