首页 > 解决方案 > 使用firebase创建用户时设置显示名称

问题描述

我有一个反应应用程序,我想用它来处理使用 firebase 的身份验证。

我的代码成功注册并登录,但我试图在注册时添加额外信息,但我没有成功。我已经尝试过答案 [这里]:Firebase v3 updateProfile Method和 [这里]:Firebase user.updateProfile({...}) not working in React App

但它们似乎不起作用。下面是我的代码

const SignUp = ({ history }) => {
  const handleSignUp = useCallback(
    async event => {
      event.preventDefault();
      const { email, password } = event.target.elements;
      try {
        let cred = await app
          .auth()
          .createUserWithEmailAndPassword(email.value, password.value);
        await cred.user.updateProfile({
          displayName: 'hello'
        });

        history.push('/');
      } catch (error) {
        console.log(error);
      }
    },
    [history]
  );

请问我该如何解决这个问题,因为目前在电子邮件和用户名集中?谢谢

标签: javascriptreactjsfirebasefirebase-authentication

解决方案


为了更改用户配置文件,您应该使用 firebase.auth().onAuthStateChanged() 函数,如下所示:

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    // User is signed in.
  } else {
    // No user is signed in.
  }
});

然后您可以获取其他用户属性。在这里您可以找到您需要的所有信息。https://firebase.google.com/docs/auth/web/manage-users。希望能帮助到你。


推荐阅读