首页 > 解决方案 > undefined 不是对象(评估 'userCredentails.user')

问题描述

我正在为我的 react 本机应用程序构建用户身份验证页面。问题我在注册用户时无法更新 displayName。之后,我需要将姓名、电子邮件、密码存储在我的 Firestore 数据库中。

我正在使用世博会和火力基地。我不明白为什么它不起作用。

import firebase from "firebase";
import { auth } from "../../firebase";

const SignUpScreen = () => {
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");

  // const user = firebase.auth().currentUser;

  // Sign Up ----------
  const handleSignUp = () => {
    auth
      .createUserWithEmailAndPassword(email, password)
      .then((userCredentials) => {
        if (userCredentials) {
          const user = userCredentials.user;
          user.updateProfile({
            displayName: name,
          });
        }
      })
      .then((userCredentials) => {
        const user = userCredentials.user;
        // console.log("Registered with:", user.email);
      })
      .catch((error) => alert(error.message));
  };

标签: reactjsfirebasereact-nativegoogle-cloud-firestorefirebase-authentication

解决方案


第一个then()块似乎没有返回任何东西。函数也updateProfile()返回一个承诺。尝试用 async-await 语法重构代码,如下所示:

const handleSignUp = async () => {
  try {
    const userCredential = await auth.createUserWithEmailAndPassword(email, password)
    const user = userCredential.user
  
    await user.updateProfile({ displayName: name })
  
    console.log("Registered with:", user.email);
  } catch (e) {
    console.log(e)
  }
}

推荐阅读