首页 > 解决方案 > 如何在 Firebase 中注册用户后立即将 displayName 添加到用户?

问题描述

我对使用useRef. 这是我的代码:

try {
  await signup(emailRef.current.value, passwordRef.current.value);
  var user = firebase.auth().currentUser;
  user.updateProfile({
    displayName: nameOfUserRef,
  });
  history.push("/");
} catch (error) {
  console.log(error);
}

我的期望:我希望新添加的用户的 displayName 将更改为nameOfUserRef

发生了什么:它没有抛出错误,但是当我控制台 log 时user.displayName,它显示null.

标签: reactjsfirebaseauthenticationfirebase-authentication

解决方案


updateProfile()方法是异步的并返回一个 Promise,因此您应该使用await,就像您对异步signup()方法所做的那样:

try {
  await signup(emailRef.current.value, passwordRef.current.value);
  var user = firebase.auth().currentUser;
  await user.updateProfile({
    displayName: nameOfUserRef,
  });
  console.log(user.displayName)  <= Should be ok here
  history.push("/");
} catch (error) {
  console.log(error);
}

推荐阅读