首页 > 解决方案 > 如何通过单击状态从 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>
    )

}

标签: javascriptreactjsreact-nativereact-native-flatlistreact-state

解决方案


问题在于您用于删除项目的功能。

map() 方法使用为每个数组元素调用函数的结果创建一个新数组。

filter() 方法创建一个数组,其中填充了所有通过测试的数组元素。

所以当你运行map((_item, _Index) => _Index !== index)你的removeItem意志是:

 [false, false, false, true, false, false, false, false, false, false, false]

一堆布尔值没有明显呈现:)

为了删除项目使用filter((_item, _Index) => _Index !== index)


推荐阅读