In React Native wird der neue Wert nicht angezeigt, nachdem das Echtzeit-Firebase-Textfeld geändert wurde.
P粉035600555
P粉035600555 2023-09-13 17:10:05
0
1
468

Ich programmiere in React Native und benötige einen Live-Wert von Google Firebase. Ich kann den Wert (1) abrufen, aber wenn sich der Wert in der Datenbank ändert, ändert sich das Textfeld in meiner Anwendung nicht entsprechend (2). Mit anderen Worten: Eine Echtzeitsynchronisation mit der Datenbank ist nicht implementiert. Ich kann nicht herausfinden, warum. Werden Sie mir mit diesem Problem helfen? Vielen Dank! Der Code, den ich geschrieben habe, lautet wie folgt:

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>   ); }

Ich brauche einen Wert von Google Firebase in Echtzeit und wenn er sich in der Datenbank ändert, muss er sich auch im Textfeld ändern.

P粉035600555
P粉035600555

Antworte allen(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:

Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!