Javascript react应用程序中的自定义firebase函数未返回值

Javascript react应用程序中的自定义firebase函数未返回值,javascript,reactjs,firebase,firebase-authentication,Javascript,Reactjs,Firebase,Firebase Authentication,我已经为我的react应用程序定制了一些firebase函数,因此我不必每次都编写整个代码。问题是,当有一个值要返回时(例如用户JSON),当我从另一个文件调用时,它不会返回该值 下面是一段不起作用的代码: Functions.js 我在我的React条目文件中调用它: App.js 我曾尝试使用普通函数而不是箭头函数,但它无法解决问题 发生的事情是,您正在访问的firebase方法是异步的,但您的代码忽略了这一点,并希望它们同步工作。本质上,函数将在等待异步操作解决时返回 您可以调用AuthS

我已经为我的react应用程序定制了一些firebase函数,因此我不必每次都编写整个代码。问题是,当有一个值要返回时(例如用户JSON),当我从另一个文件调用时,它不会返回该值

下面是一段不起作用的代码:

Functions.js

我在我的React条目文件中调用它: App.js


我曾尝试使用普通函数而不是箭头函数,但它无法解决问题

发生的事情是,您正在访问的firebase方法是异步的,但您的代码忽略了这一点,并希望它们同步工作。本质上,函数将在等待异步操作解决时返回

您可以调用
AuthState
。启动操作
firebase.auth().onAuthStateChanged
,等待firebase完成其任务并返回。在此之前,将执行函数中的其余行。没有,因此返回一个未定义的。稍后,将触发传递给onAuthStateChanged的回调,但该回调不绑定任何内容,因此无法访问解析的返回值

要在操作实际完成后触发某些代码,可以将代码更改为使用异步构造(回调或承诺)

回调:

const AuthState = (cb) => {
  firebase.auth().onAuthStateChanged(user => {
    if (user) {
      cb(user);
    } else {
     cb(null);
    }
  });
};
现在,将异步操作的计时与React的呈现方法集成是一个复杂的过程,但要复杂得多。不要将这样的异步代码放入
componentDidMount
属性中。这可能会导致无限的更新循环。相反,可以在构造函数中初始化,也可以在用户触发时调用(即单击按钮或按enter键):


firebase.auth().onAuthStateChanged接收回调。在该回调中,返回用户。我建议您熟悉回调,应该很容易找到解决方案。试试我刚才试过了,但它不起作用!
import {AuthState} from './Functions'

class App extends Component {
  componentDidMount() {
    const result = AuthState();
    console.log(result) // Undefined
  }
  ...
const AuthState = (cb) => {
  firebase.auth().onAuthStateChanged(user => {
    if (user) {
      cb(user);
    } else {
     cb(null);
    }
  });
};
import {AuthState} from './Functions'

class App extends Component {
  constructor(super) {
    props(super)
    this.state = {
      result = null
    }
    // get the results of component render initialization:
    AuthState(res => {
      this.setState({
        result: res
      })
      console.log(res)
    });

    // or you can wrap that in a function for attaching to DOM event listeners: 
    this.clickHandler = e => {
      AuthState(res => {
        this.setState({
          result: res
        })
        console.log(res)
      });
    }
  }
  ...