首页 > 解决方案 > React-Native - 无法将 displayName 和 photoURL 保存到 firebase

问题描述

在我的 react native 项目中注册期间,我发现很难将用户的 displayName 和 photoURL 保存到 firebase。

我使用文档(https://firebase.google.com/docs/reference/js/firebase.User.html#updateprofile)作为指南。

请参阅下面我的代码:

  onRegister = () => {
  firebase.auth().createUserWithEmailAndPassword( this.state.typedEmail, this.state.typedPassword)
  .then((userCredentials) => {
    if(userCredentials.user) {
      console.warn(userCredentials.user)
      userCredentials.user.updateProfile({
        displayName: "Jane Q. User",
        photoURL: "https://example.com/jane-q-user/profile.jpg"
      })
      .then(() => {
        this.setState({ user: userCredentials.user })
        console.warn("yo:", this.state.user)
      })
    }
  }).catch((error) => {
      console.warn(`error:, ${error}`)
  })}

使用上述功能,我可以保存电子邮件和密码,但 displayName 和 photoURL 仍然返回 null。

请帮忙。

标签: reactjsfirebasereact-nativefirebase-authenticationreact-native-android

解决方案


您可以尝试重新加载然后获取当前用户

async function updateProfile() {
  await firebase.auth().currentUser.updateProfile({
        displayName: "Jane Q. User",
        photoURL: "https://example.com/jane-q-user/profile.jpg"
      });
  await firebase.auth().currentUser.reload();
  console.log(firebase.auth().currentUser.displayName); <-- check if it is updated
}

更新

onRegister = async () => {
  try {
    const userCredentials = await firebase
      .auth()
      .createUserWithEmailAndPassword(this.state.typedEmail, this.state.typedPassword);
    if (userCredentials.user) {
      console.warn(userCredentials.user);
      await userCredentials.user.updateProfile({
        displayName: 'Jane Q. User',
        photoURL: 'https://example.com/jane-q-user/profile.jpg',
      });
      await userCredentials.user.reload();
      this.setState({ user: firebase.auth().currentUser });
      console.warn('yo:', this.state.user);
    }
  } catch (error) {
    console.warn(`error:, ${error}`);
  }
};

推荐阅读