猿问

创建帐户后 displayName 始终返回 null

我有一个使用 Firebase 作为后端的 Vue 应用程序。新用户使用电子邮件和密码选项注册。这是 firebase 方法:


firebase.auth()

          .createUserWithEmailAndPassword(this.user.email, this.user.password)

          .then((res) => {

            res.user

              .updateProfile({

                displayName: this.user.username,

              })

              .then(() => {

              });

          })

          .catch((error) => {

            this.error = error.message;

            console.log("err", error);

          });

在我的 main.js 文件中,我有如下所示的 onAuthStateChanged 方法:


firebase.auth().onAuthStateChanged((user) => {

  if (user) {

    console.log("user", user);

    console.log("nme", user.displayName);

    console.log("email", user.email);

    store.dispatch("fetchUser", user);

  } else {

    store.dispatch("logout");

  }

当用户注册时,当然会触发此方法。问题是我无法访问用户的 displayName 属性,由于某种原因,当用户注册时它总是空的。当我刷新页面时,它有值,但在注册它的 null 并将 null 值作为用户名传递给 Vuex 之后。奇怪的是,例如可以立即访问电子邮件。这是我的控制台的屏幕截图:

第一部分是“console.log("user", user),然后是其他打印。正如您在用户对象中看到的那样,displayName 有一个值,但是当我调用 user.displayName 时,它为空。

有人可以向我解释为什么会这样吗?提前致谢!


扬帆大鱼
浏览 126回答 1
1回答

慕森王

这是因为该updateProfile()方法是异步的,不会触发通过 设置的监听器onAuthStateChanged()。因此,当onAuthStateChanged()在创建用户(并登录,因为在创建用户帐户之后,用户也已登录)后立即触发侦听器时, 的值尚未更新displayName。当方法返回的承诺updateProfile()得到解决时,您可能应该更新 Vuex Store 中的状态。以下几行: firebase    .auth()    .createUserWithEmailAndPassword(this.user.email, this.user.password)    .then((res) => {      return res.user.updateProfile({        displayName: this.user.username,      });    })    .then(() => {      //Update the Vuex Store here with firebase.auth().currentUser      console.log(firebase.auth().currentUser.displayName);    })    .catch((error) => {      this.error = error.message;      console.log('err', error);    });
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答