搜尋

首頁  >  問答  >  主體

React Native中,即時Firebase文字欄位變更後,未顯示新值的問題

我正在使用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中取得一個值,並且當它在資料庫中發生變化時,我需要它在文字方塊中也發生變化。

P粉035600555P粉035600555527 天前597

全部回覆(1)我來回復

  • P粉670838735

    P粉6708387352023-09-14 14:28:02

    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:

    1. Store the data in the state of your component
    2. Tell ReactJS to rerender the component when the state changes

    The common way to do this is by using the useState and useEffect hooks.

    const [data, setData] = useState();
    
    // Putting the code to load from Firebase in a useEffect call 
    // with no dependencies (the empty array at the end) ensure it
    // only runs once, when the component is first rendered.
    useEffect(() => {
      database()
        .ref('/esp01_1/id')
        .on('value', snapshot => {
          // Calling setData puts the data in the component's state
          // and tells ReactJS to rerender the UI.
          setData(snapshot.val());
        });
    }, []);

    This is a quite complex topic, so I recommend reading up on both of the hooks used here and also see:

    回覆
    0
  • 取消回覆