Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript currentUser显示为未定义,但稍后定义。这在另一个组件中有效,但不是这个特定组件,我不确定_Javascript_Reactjs_Firebase_Firebase Authentication - Fatal编程技术网

Javascript currentUser显示为未定义,但稍后定义。这在另一个组件中有效,但不是这个特定组件,我不确定

Javascript currentUser显示为未定义,但稍后定义。这在另一个组件中有效,但不是这个特定组件,我不确定,javascript,reactjs,firebase,firebase-authentication,Javascript,Reactjs,Firebase,Firebase Authentication,我正试图从数据库中获取当前用户信息。然而,出于某种奇怪的原因,它说currentUser未定义,但当我调试时,它是在调用函数后定义的。有什么办法可以解决吗 setResults(){ const user = (this.props.firebase.auth.currentUser) ? this.props.firebase.auth.currentUser.uid : null ; if(user){ this.props.firebase.result(this.

我正试图从数据库中获取当前用户信息。然而,出于某种奇怪的原因,它说currentUser未定义,但当我调试时,它是在调用函数后定义的。有什么办法可以解决吗

setResults(){
    const user = (this.props.firebase.auth.currentUser) ? this.props.firebase.auth.currentUser.uid : null ;
    if(user){
    this.props.firebase.result(this.props.firebase.auth.currentUser.uid).on('value', snapshot => {
      const resultObj = snapshot.val();
      if(resultObj) {
        const resultList = Object.keys(resultObj).map(key => ({
          ...resultObj[key],
        }));
        this.setState({
          result: resultList,
        loading: false,
        });
      }else{
        this.setState({ results: null, loading: false});
      }
    })
  }
}

  componentDidMount() {
    this.setState({ loading: true});
    this.setResults();
  }
firebase.auth.currentUser总是在代码开始在网页加载上运行时未定义。如果一个用户在短时间后实际登录,则将使用该用户的身份填充该用户

您应该做的是在用户的登录状态已知时使用设置回调。代码应该使用此回调来确定何时知道用户对象,以及何时开始基于该用户的数据呈现内容

firebase.auth.onAuthStateChanged(function(user) {
  if (user) {
    // User is signed in.
    var displayName = user.displayName;
    var email = user.email;
    var emailVerified = user.emailVerified;
    var photoURL = user.photoURL;
    var isAnonymous = user.isAnonymous;
    var uid = user.uid;
    var providerData = user.providerData;
    // ...
  } else {
    // User is signed out.
    // ...
  }
});