【发布时间】:2020-09-07 17:54:34
【问题描述】:
我正在创建一个应用程序,允许用户从Flatlist 中选择多个项目,并且一旦选择,state 就会更改。但是,当我离开该屏幕时,所有 选定 项目都会返回 未选定 状态。如何使用Firebase 来保存state,这样当我离开屏幕时它就不会恢复?我也对这个问题的替代解决方案持开放态度。
感谢您的宝贵时间。
export default function StoreCatalogue({ navigation }) {
const { data, status } = useQuery('products', fetchProducts)
const [catalogueArray, setCatalogueArray] = useState([])
const [isSelected, setIsSelected] = useState([])
const [addCompare, setAddCompare] = useState(false)
const storeToDB = async (item) => {
if (!addCompare) {
await db.collection('users').doc(auth.currentUser.uid).collection('myProducts').doc(item.storeName + item.genName).set({
product_id: item.id,
product_genName: item.genName
})
} else {
await db.collection('users').doc(auth.currentUser.uid).collection('myProducts').doc(item.storeName + item.genName).delete()
}
}
const clickHandler = async (item) => {
setAddCompare(
addCompare ? false : true
)
if (isSelected.indexOf(item) > -1) {
let array = isSelected.filter(indexObj => {
if (indexObj == item) {
return false
}
return true
})
setIsSelected(array)
} else {
setIsSelected([
...isSelected, item
])
}
}
return (
<View style={styles.container}>
<FlatList
extraData={isSelected}
keyExtractor={(item) => item.id}
data={catalogueArray}
renderItem={({ item }) => (
<TouchableOpacity style={styles.btn} onPress={() => { storeToDB(item); clickHandler(item) }}>
<MaterialCommunityIcons name='plus-circle-outline' size={24} color={isSelected.indexOf(item) > -1 ? 'grey' : 'green'} />
<View style={{ position: 'absolute', bottom: 3 }}>
<Text style={{ fontSize: 10, textAlign: 'center', color: isSelected.indexOf(item) > -1 ? 'grey' : 'green' }}>{isSelected.indexOf(item) > -1 ? 'item \nAdded' : 'Add to\n Compare '}</Text>
</View>
</TouchableOpacity>
)}
/>
</View>
)
}
【问题讨论】:
-
将你的状态保存在 redux 存储中怎么样?
-
嗨@Andrew 我以前从未使用过 Redux... 有没有办法用 Context Api
useContext做到这一点? -
好的,那么我建议使用 useContext + hooks 来存储全局状态:medium.com/@pgivens/…
-
@Andrew 非常感谢这篇文章对您很有帮助。完成后我会发布解决方案。谢谢
标签: javascript firebase react-native expo asyncstorage