我试图通过单击每个项目来删除 FlatList 中的项目,但这对我不起作用,当我单击每个项目时,什么也没有发生,也没有收到任何错误。 我该如何解决这个问题?
这是我的代码:(我删除了不必要的代码和样式)
const FoodList = () => {
const data= [
{ text: 'test' },
{ image: 'https://via.placeholder.com/200x100' },
{ text: 'test' },
{ text: 'test' },
{ text: 'test' },
{ text: 'test' },
{ text: 'test' },
{ text: 'test' },
{ text: 'test' },
]
let [itemState, setitemState] = useState(data);
return (
<View>
<FlatList
data={data}
keyExtractor={(item, index)=>index}
renderItem={({ item }) => (
<TouchableOpacity>
<View>
<Text>{item.text}</Text>
<Image source={{ uri: item.image}}
/>
</View>
<Icon
onPress={(index)=>setitemState(itemState=itemState.filter(item=>item.index!==index))} />
</TouchableOpacity>
)}
/>
</View>
)}
最佳答案
首先,正如 @Hamza Khattabi 所提到的,您需要在 data
属性中使用 itemState
来实际使用更新后的状态,否则没有任何使用意义setitemState
,仅修改itemState
状态。
其次,我认为 item.index
根本不会返回任何内容,而且我非常有信心 onPress={(index) => {...}
也不会返回任何 Icon
元素中的 }index
。 您将可以使用 renderItem
属性中的 index
,如 this link 的文档中所述。 .
考虑到这些更改后,您可以简单地过滤掉 itemState
状态以删除索引处的元素。有许多不同的方法可以删除索引处的元素,但这里是一个可能的解决方案:
<FlatList
data={itemState} // Note the use of itemState
keyExtractor={(item, index) => index}
renderItem={({ item, index }) => ( // Note the use of index
<TouchableOpacity>
<View>
<Text>{item.text}</Text>
<Image source={{ uri: item.image }} />
</View>
<Icon
onPress={() => { // Note that here you can use any function to remove the element at index from the itemState list
let _itemState = itemState.filter(
(_item, _index) => _index !== index
);
setitemState(_itemState);
}}
/>
</TouchableOpacity>
)}
/>
请在下面发表评论,让我知道这是否对您有帮助。
关于javascript - 我无法通过 useState Hook 从 FlatList 中删除项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60551607/