我正在使用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: