简体   繁体   English

Firebase | 从 Firebase 读取数据返回“未定义”,但 console.log 显示精确结果

[英]Firebase | Reading data from Firebase returns "undefined", but console.log shows precise result

EDIT: I'm new to Stack, but why was my earlier thread locked?编辑:我是 Stack 的新手,但为什么我之前的线程被锁定了? It just said "similar thread is found somewhere else" and the thread wasn't at all similar.它只是说“在其他地方发现了类似的线程”,而该线程根本不相似。

I am currently trying to update my own little personal weight tracker using Firebase and React Native.我目前正在尝试使用 Firebase 和 React Native 更新我自己的小型个人体重追踪器。 However, whenever I log DataSnapshot.val() I receive the input 22 , which is perfect.但是,每当我记录DataSnapshot.val()时,我都会收到输入22 ,这是完美的。 But when I return the very same value I receive Undefined .但是当我返回完全相同的值时,我收到了Undefined

I tried both get() and onValue() with the same results.我尝试了get()onValue() ,结果相同。 The path is correct, since I get the correct data using console.log.路径是正确的,因为我使用 console.log 获得了正确的数据。

https://firebase.google.com/docs/database/web/read-and-write?authuser=2 https://firebase.google.com/docs/database/web/read-and-write?authuser=2

I tried following the above documentation.我尝试按照上述文档进行操作。 But is it updated?但是更新了吗? snapshot is currently DataSnapshot ? snapshot当前是DataSnapshot吗?

Firebase: Firebase:

const readWeight = (database, userId) => {
  get(ref(database, `users/${userId}/weight`)).then((DataSnapshot) => {
    try {
      if (DataSnapshot.exists()) {
        console.log(
          `Weight found. Current weight is: ${DataSnapshot.val()} kg`
        );
        return DataSnapshot.val();
      } else {
        console.log("Weight wasn't found");
      }
    } catch (error) {
      console.log(error);
    }
  });
};

HomeScreen.js HomeScreen.js

// Modules
import { react, useState, useEffect } from "react";
import { Text, TouchableOpacity, View, TextInput, Image } from "react-native";
import { LogOutButton } from "../Components/LogOutButton";
import { auth, writeUserData, database, readWeight } from "../firebase";

// Stylesheet
import { styles } from "../Stylesheet/Stylesheet";

export const HomeScreen = () => {
  const user = auth.currentUser;

  let currentUserWeight = readWeight(database, user.uid);


  console.log("Current Weight: ", currentUserWeight);


  return (
    <View style={styles.profileMain}>
      <View style={styles.profileInfoContainer}>

        <View style={styles.HOME__profileWeightContainer}>

          <Text style={styles.HOME__profileWeightText}>
            Last Weight: {currentUserWeight}
          </Text>

        </View>
      </View>
      </View>
    </View>
  );
};

Data is loaded from Firebase asynchronously, and the return DataSnapshot.val() runs way after you actually call readWeight(database, user.uid) .数据从 Firebase 异步加载, return DataSnapshot.val()在您实际调用readWeight(database, user.uid)之后运行。 Adding some logging is probably the best way to see that flow.添加一些日志记录可能是查看该流程的最佳方式。

The solution is to store the weight in the state of your component with the useState hook.解决方案是使用 useState 挂钩将权重存储在组件的useState中。

export const HomeScreen = () => {
  const user = auth.currentUser;

  // 👇
  let { currentUserWeight, setCurrentUserWeight } = useState(0);

  useEffect(() => {
    const unsubscribe = get(ref(database, `users/${userId}/weight`)).then((DataSnapshot) => {
      if (DataSnapshot.exists()) {
        setCurrentUserWeight(DataSnapshot.val());
      }
    });  
    return () => unsubscribe();
  , []}
  // 👆

  return (
    <View style={styles.profileMain}>
      <View style={styles.profileInfoContainer}>

        <View style={styles.HOME__profileWeightContainer}>

          <Text style={styles.HOME__profileWeightText}>
            Last Weight: {currentUserWeight}
          </Text>

        </View>
      </View>
      </View>
    </View>
  );
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM