如何通过导出功能从Firebase实时数据库中获取用户孩子的价值

如何通过导出功能从Firebase实时数据库中获取用户孩子的价值

问题描述:

例如,我正尝试使用从我的database.js帮助程序文件导入到主要导航为以下内容的类组件的功能来获取用户的电话号码:

I'm trying to get my users's phone number for example, with a function that I import from a database.js helper file to a class component where my main navigation is:

import * as React from "react";
import { NavigationContainer } from "@react-navigation/native";
import { AuthStack } from "./AuthStack";
import { TabNavigator } from "./TabNavigator";
import { ProfileAuthStack } from "./ProfileAuthStack";
import firebase from "../util/firebase";
import { AppLoading } from "expo";
import { getPhone } from "../util/database";

export default class AppNavigator extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      user: "",
      isLoading: false,
    };
  }

  async componentDidMount() {
    var name, email, phone;
    firebase.auth().onAuthStateChanged((user) => {
      if (user) {
        name = user.displayName;
        email = user.email;
        phone = getPhone(user.uid);

        console.log(name + " " + email + " " + JSON.stringify(phone));
        this.setState({ user });
      } else {
        console.log("not logged in");
        this.setState({ user: "" });
      }
    });
  }

  render() {
    if (this.state.isLoading) {
      return <AppLoading />;
    } else {
      return (
        <NavigationContainer>
          {this.state.user ? (
            this.state.isAdmin ? (
              <TabNavigator />
            ) : (
              <ProfileAuthStack />
            )
          ) : (
            <AuthStack />
          )}
        </NavigationContainer>
      );
    }
  }
}

这是我的功能:

import firebase from "./firebase";

//THIS IS THE FUNCTION \/
export const getPhone = function (uid) {
  var phone;
  var userRef = firebase.database().ref("users/" + uid);
  userRef.on("value", function (snapshot) {
    phone = snapshot.val().phone;
    return phone;
  });
};

现在我的 console.log 看起来像这样:

now my console.log looks like this:

Nikola niko@gmail.com undefined

我不明白为什么我要找回未定义的值而不是值本身我在做什么错了?

I can't understand why I'm getting back an undefined instead of the value itself What Am I doing wrong?

我在数据库中的JSON树如下:

my JSON tree in the database looks like this:

{
  "admins" : {
    "lessons" : ""
  },
  "users" : {
    "96GFQRlNQwQOu7zEEx7Gqp94NVq1" : {
      "admin" : false,
      "credit" : 0,
      "injuries" : "",
      "isProfileFilled" : true,
      "isValid" : false,
      "phone" : "123123123"
    }
  }
}

数据是从Firebase异步加载的.任何需要数据的代码都必须位于回调中或从那里被调用.

Data is loaded from Firebase asynchronously. Any code that needs the data needs to either be in the callback or get called from there.

您的代码可能是这样的:

Your code could be something like this:

export const getPhone = function (uid) {
  var userRef = firebase.database().ref("users/" + uid);
  return userRef.once("value").then(function (snapshot) {
    var phone = snapshot.val().phone;
    return phone;
  });
};

然后:

firebase.auth().onAuthStateChanged((user) => {
  if (user) {
    name = user.displayName;
    email = user.email;
    getPhone(user.uid).then(function(phone) {
        console.log(name + " " + email + " " + JSON.stringify(phone));
        this.setState({ user });
    });
  } else {
    console.log("not logged in");
    this.setState({ user: "" });
  }
});

因此,这里的更改是:

  • getPhone 函数使用 once()而不是 on ,因为它只需要从数据库获取一次值.
  • li>
  • 这意味着我们现在可以使用一次返回的 then(),然后通过返回 return userRef ...使返回电话冒泡.(来自 getPhone ).
  • 现在,您对 getPhone 的呼叫将获得一个诺言,我们将通过一个 then()块来处理该诺言.在唯一可以安全使用 phone 的地方,所以现在我们就可以记录它并设置状态了.
  • The getPhone function uses once() instead of on, since it only needs to get the value from the database once.
  • This means we can now use the then() returned by once, and we then bubble up the return phone by also returning return userRef... out of getPhone.
  • Now your call to getPhone gets back a promise, which we handle with a then() block. In there is the only place we can safely use phone, so that's where we now log it and set the state.

这是一个非常常见的问题,所以我建议阅读其中的一些内容:

This is an incredibly common problem, so I recommend reading some of these:

  • MDN documentation on async functions
  • How do I return the response from an asynchronous call?
  • How to return values from async functions using async-await from function?, which uses the async and await keywords that reduce the nesting.
  • Best way to retrieve Firebase data and return it, or an alternative way
  • Firebase query function returns undefined