【发布时间】:2021-09-15 17:10:18
【问题描述】:
我意识到有很多关于这个的问题和答案,但我对 react native 还很陌生,大多数答案都是关于 React 组件而不是钩子。在以下示例中,availableInterests 是从 firestore 数据库调用中提取的。然后我们遍历 availableInterests,以便用户可以从 Flatlist of Interests 中选择他们的兴趣。一切都很好,除了 FLatlist 不会重新渲染,因此用于选择 currentInterests 的按钮永远不会显示已选择兴趣的更改。有人看到我在这里缺少什么吗?
const [availableInterests, setAvailableInterests] = useState([]);
const [currentInterests, setCurrentInterests] = useState([]);
const selectThisInterest = (item) => {
let myInterests = currentInterests;
if(myInterests.includes(item.id)) {
myInterests.pop(item.id);
} else {
myInterests.push(item.id);
}
setCurrentInterests(myInterests);
}
return <View>
<Text style={styles.text}>Select Your Interests:</Text>
<FlatList
data={availableInterests}
keyExtractor={(item, index) => index.toString()}
extraData={currentInterests}
renderItem={({ item, index }) =>
<View key={item.id}>
<Text>{item.title}</Text>
<Text>{item.description}</Text>
<Image
source={{ uri: item.icon }}
style={{ width: 100, height: 100}}
/>
<TouchableOpacity onPress={() => selectThisInterest(item)}>
<Text style={styles.buttonText}>{`${currentInterests.includes(item.id) ? 'UnSelect' : 'Select'}`}</Text>
<Text>{item.id}</Text>
</TouchableOpacity>
</View>
}>
</FlatList>
</View>
【问题讨论】:
标签: react-native react-hooks react-native-flatlist