React Native中,即時Firebase文字欄位變更後,未顯示新值的問題
P粉035600555
P粉035600555 2023-09-13 17:10:05
0
1
469

我正在使用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粉035600555
P粉035600555

全部回覆(1)
P粉670838735

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:

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!