【问题标题】:Function undefined when assigned to variable分配给变量时函数未定义
【发布时间】:2016-04-17 07:11:16
【问题描述】:

我正在使用 Firebase 作为后端在 React 中进行一些身份验证。

我有一个功能可以检查是否存在按我预期工作的用户:

checkIfUserExists(uid) {
  ref.child('users').child(uid).once('value', function(snapshot) {
    if (snapshot.exists()) {
      console.log("User exists");
      return true;
    } else {
      console.log("User does not exist");
      return false;
    }
  });
}

当我通过 uid 调用它时,如果用户存在或不存在,它将写入控制台。

this.checkIfUserExists(userId);

我只想获取用户是否登录的布尔表示,但尝试执行此类操作将始终打印“无用户”。

if (this.checkIfUserExists(userId)) {
  console.log('The user does really exist');
} else {
  console.log('No user');      
}

如果我尝试

console.log(this.checkIfUserExists(userId));

控制台输出“未定义”。

我是不是以错误的方式处理这个问题?为什么未定义?

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    内部函数内部的return语句不会通过外部函数返回值。而是尝试发送这样的函数

    checkIfUserExists(uid, callback) {
      ref.child('users').child(uid).once('value', function(snapshot) {
        callback.call(null, snapshot.exists());
      });
    };
    
    checkIfUserExists(uid, function(exists){
      if(exists){
        console.log("User exists");
      }else{
        console.log("User does not exist"); 
      }
    });
    

    More on .call() here in documentation

    【讨论】:

    • 谢谢!这就说得通了。我现在开始掌握回调的概念了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-20
    • 2016-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多