![](/img/trans.png)
[英]How to properly unsubscribe to an onValue listener for Firebase Realtime Database
[英]how to get the object returned by firebase onValue()
我對本機反應和一般的前端開發還比較陌生,所以請多多包涵。 我正在編寫一個簡單的反應本機應用程序,它從 firebase 檢索 map 標記的數據並將它們顯示在 map 上。我編寫了一個 python 程序,它定期向 firebase 添加新標記,這意味着存儲在數據庫中的數據不是 80.682按照來自谷歌的文檔並通過事件偵聽器讀取數據在我的應用程序中工作正常,但我無法將 object 的數據存儲在 onValue 之外的變量中。 我的問題是如何從數據庫中獲取檢索到的數據,並將其顯示在 map 視圖上?
這是我的代碼:
import React, { useEffect, useState } from 'react'
import { FlatList, Keyboard, Text, TextInput, TouchableOpacity, View, Dimensions} from 'react-native'
import styles from './styles';
import MapView from 'react-native-maps';
import { Marker } from "react-native-maps";
import { getDatabase, ref, onValue } from 'firebase/database';
import { firebase} from '../../firebase/config'
import { app} from '../../firebase/config'
export default function HomeScreen(props) {
const db = getDatabase();
const f1 = ref(db, '/');
onValue(f1, (snapshot) => {
const data = snapshot.val();
});
const uniRegion = {
latitude: 25.2863943,
longitude: 55.4749801,
latitudeDelta: 0.0922,
}
return (
<View style={styles.container}>
<MapView style={styles.map} region={uniRegion}
showsUserLocation={true} >
<Marker coordinate={uniRegion} />
</MapView >
</View>
);
}
您可以將數據存儲在您想要的任何變量中,但需要確保 React 在加載或更新數據時重新呈現其 UI。 為此,您需要使用useState
掛鈎將數據存儲在 state 中。
對於這方面的一些例子:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.