如何显示用户名

How to display user name

我正在使用 Google Firebase 作为我的后端。我有一个用户填写的注册表。

进程成功后,用户将被定向到主页,其中应显示:

“欢迎,{user's firstName}

const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [firstName, setFirstName] = useState('');
const [lastName, setLastName] = useState('');
const [phoneNum, setPhoneNum] = useState('');

const onSignUp = () => {
    auth
        .createUserWithEmailAndPassword(email, password)
        .then(userCredentials => {
            firebase
                .firestore()
                .collection('users')
                .doc(firebase.auth().currentUser.uid)
                .set({
                        firstName,
                        lastName,
                        email,
                        phoneNum
                });
            const user = userCredentials.user;
            console.log('Registered with:', user.email);
            console.log(user.firstName);
        })
        .catch(error => console.log(error.message));
  };

当我控制日志 user.email 时它工作,但是当我控制日志 firstName 时,它记录为未定义。 当我检查 firebase 时,它​​已注册用户并填充了所有字段(firstName、lastName、phoneNum)

如何检索用户的名字?

您正在尝试从 Firebase 身份验证用户数据中访问未在此处定义的信息。

重构代码如下:

const onSignUp = () => {
  auth
    .createUserWithEmailAndPassword(email, password)
    .then(async (userCredentials) => {
      const usersRef = firebase.firestore().collection("users");
      const user = userCredentials.user;
      const userId = user.uid;

      // Add new user to USERS' collection

      await usersRef.doc(userId).set({
        userId,
        firstName,
        lastName,
        email,
        phoneNum,
      });

      // Fetch registered user information

      const userDoc = await usersRef.doc(userId).get();

      const regiteredUser = userDoc.data();

      console.log(
        "Registered with:",
        regiteredUser.email,
        regiteredUser.firstName,
        firstName.lastName
      );
    })
    .catch((error) => console.log(error.message));
};