Firebase用户displayName为null

时间:2018-05-17 11:26:13

标签: javascript reactjs firebase firebase-authentication

我在我的反应应用程序中运行此代码:

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>

<body>

<div class="container">

  <div class="btn btn-primary">Primary</div>
     
</div>

这是modelInstance.getSignInStatus():

  componentDidMount() {
    modelInstance.addObserver(this);
    modelInstance.getSignInStatus().then((user)=>{
      this.setState({
        userName: user !== false ? user.displayName : "Sign in",
        logged_in: user !== false ? true : false

      });
    });
  }

this.getSignInStatus = function () { return new Promise((resolve, reject)=>{ firebase.auth().onAuthStateChanged(function(user){ if (user){ resolve(user); } else { resolve(false); } }); }); } 设置为this.state.userName,意味着nulluser.displayName。这是为什么?

2 个答案:

答案 0 :(得分:1)

  state = {
    username: "",
    email: "",
    passwordOne: "",
    passwordTwo: "",
    error: null
  }; 

  onSubmit = event => {
    const {username, email, passwordOne} = this.state;
    const {history} = this.props;

    auth
      .createUserWithEmailAndPassword(email, password);
      .then(authUser => {
        db.doCreateUser(authUser.uid, username, email).then(() => {
          //you should clear your state fields here, for username / email etc
          console.log(authUser);
          //redirect user
          history.push(routes.HOME);
        });
      })
      .catch(error => {
        this.setState({error});
      });
    event.preventDefault();
  };

const auth = firebase.auth();

const db = firebase.database(); 为了获取doCreateUser

const doCreateUser = (id, username, email) =>
  db.ref(`users/${id}`).set({
    uid:id,
    username,
    email,
  });

答案 1 :(得分:0)

我会使用setState来检查auth状态,如下所示:

firebase.auth().onAuthStateChanged(function(user){
    if (user){
      this.setState({user});
    }
}

然后你想要当前用户的displayName状态

componentDidMount() {
 modelInstance.addObserver(this);
 modelInstance.getSignInStatus().then((user)=>{
   this.setState({
     userName: this.state.user ? this.state.user.displayName : "Sign in",
     logged_in: this.state.user ? true : false
   });
 });
}

显然,displayName属性中必须有一个名称,如果不是,则必须更新它。让我知道这是怎么回事。