首页 > 解决方案 > Firebase / React:onAuthStateChanged()是在注册功能之前还是之后触发的?

问题描述

好吧,伙计们,这真的很奇怪。

我有一个App班级和一个SignInWithPassword班级。只要没有用户登录,SignInWithPassword就会呈现出来。我有一个表单,用户可以在其中输入他们选择的用户名、电子邮件和密码,然后注册。Appuser在 App 的状态中有一个对象,该对象设置在onAuthStateChanged. 我一直面临设置 displayName 的问题,App.state.user.displayName因为当您仅使用电子邮件和密码登录时,firebase 的默认user.displayName设置为null. 我尝试使用updateProfile但仍然没有设置App's user.displayName,它只更新了 firebase 的user对象,并且 updateProfile 不会触发 onAuthStateChanged。那么,我想我会尝试在里面创建一个 setDisplayName 方法App,将它作为道具传递给SignInWithPasswordthen. 但这仍然不会改变,App.user.displayName除非我刷新它。在进行一些日志记录后,我注意到了一些奇怪的事情。

我有 3console.log()秒。一种 insideSignInWithPasswordsignUp方法:

signUp = () => {
    firebase.auth().createUserWithEmailAndPassword(this.state.email, this.state.password).then(() => {
      console.log(firebase.auth().currentUser) //log 1
      firebase.auth().currentUser.updateProfile({
        displayName: this.state.username,
      })
      this.props.setUsername(this.state.username)
    }).catch((error) => {
      // Handle Errors here.
      alert(error.message)
      this.setState({
        email: '',
        password: '',
      })
    }) 
  }

一个在里面onAuthStateChangedApp

firebase.auth().onAuthStateChanged((user) => {
      if (user) {
        console.log(user.displayName) //log 2
        const currentUser = {
          displayName: user.displayName,
          email: user.email,
          uid: user.uid,
        }
        this.setState({
          user: currentUser,
        })
      } else {
        this.setState({
          user: {}
        })
      }
    })
  }

和一个 insideAppsetUsername()方法:

setUsername = (username) => {
    const user = Object.assign({}, this.state.user)
    user.displayName = username
    this.setState({
      user,
    })
    console.log(this.state.user.displayName) //log 3
  }

显示日志的顺序是日志 1、日志 3、日志 2。这显然意味着 onAuthStateChanged 仅thensignUp. 这意味着log 2应该打印用户在表单中输入的用户名,对吗?错误的。它打印null。有人可以解释发生了什么吗??

标签: javascriptreactjsfirebasefirebase-authentication

解决方案


几个小时前我遇到了这个问题,我改变了

firebase.auth().currentUser.updateProfile({

 auth.doCreateUserWithEmailAndPassword(email, passwordOne)
    .then(authUser => {
    this.setState(() => ({ ...INITIAL_STATE }));
    authUser.user.updateProfile({
        displayName: firstName + " "+lastName
      })

它以这种方式对我有用,而不是 .currentUser


推荐阅读