React Native中,实时Firebase文本字段更改后,未显示新值的问题
P粉035600555
P粉035600555 2023-09-13 17:10:05
[React讨论组]

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

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号