我正在使用React Native進行編碼,並且需要從即時的Google Firebase中取得一個值。我能夠獲取到這個值(1),但是當資料庫中的值發生變化時,我的應用程式中的文字方塊沒有相應地變化(2)。換句話說,它與資料庫的即時同步沒有實現。我無法弄清楚原因。你能幫我解決這個問題嗎?非常感謝!我寫下的程式碼如下:
import React, { useState } from 'react'; import { View, Text, TextInput} from 'react-native'; import { NavigationContainer } from '@react-navigation/native'; import { createNativeStackNavigator } from '@react-navigation/native-stack'; import { ImageBackground, StyleSheet, Pressable, Image } from 'react-native'; import { Slider } from '@react-native-assets/slider' import { Linking } from 'react-native' import database from '@react-native-firebase/database'; var Data = ""; function Room({ navigation, route }) { //(1) database() .ref('/esp01_1/id') .on('value', snapshot => { console.log('data from firebase: ', snapshot.val()); Data = snapshot.val() }); return ( <View style={styles.container}> //(2) <Text style={styles.text}>{Data}</Text> </View> ); }
我需要從即時的Google Firebase中取得一個值,並且當它在資料庫中發生變化時,我需要它在文字方塊中也發生變化。
This is because data is loaded from Firebase (and pretty much any modern cloud API) asynchronously, and is not yet available when your
<Text style={styles.text}>{Data}</Text>
is executed.You'll want to:
The common way to do this is by using the
useState
anduseEffect
hooks.This is a quite complex topic, so I recommend reading up on both of the hooks used here and also see: