【问题标题】:{React Native} Firebase - updating user values before navigation only work after soft refresh{React Native} Firebase - 导航前更新用户值仅在软刷新后有效
【发布时间】:2020-05-13 05:41:09
【问题描述】:

我有这个简单的代码

 state = { email: '', password: '', userName: '', errorMessage: null }

handleSignUp = () => {     
  firebase.auth().createUserWithEmailAndPassword(this.state.email, this.state.password).then((userInfo) =>{ 
      userInfo.user.updateProfile({displayName: this.state.userName}).then((s) => {this.props.navigation.navigate('Navigator')})
  })
    .catch(error => this.setState({ errorMessage: error.message }))
}

在应用导航到导航器屏幕之前,一切都按预期进行。 在这里,当我登录 firebase.auth() 时,我得到了这个对象:

  Object {
        "displayName": null,
        "email": "test6@gmail.com",
        "phoneNumber": null,
        "photoURL": null,
        "providerId": "password",
        "uid": "test6@gmail.com",
      },

注意displayName 是如何为空的。

这就是问题所在......只有在软刷新后我才能得到:

  Object {
    "displayName": "Bro",
    "email": "test6@gmail.com",
    "phoneNumber": null,
    "photoURL": null,
    "providerId": "password",
    "uid": "test6@gmail.com",
  },

注意displayName 现在有一个值。

我错过了什么?我是否以错误的顺序使用.then()?承诺顺序不正确吗?

感谢任何建议!

【问题讨论】:

  • 添加 setTimeout 导航以测试是否存在异步问题 userInfo.user.updateProfile({displayName: this.state.userName}).then((s) => {setTimeout(() => { this.props.navigation.navigate('Navigator')}, 2000)})
  • 你可以试试 setTimeout,然后我们将转向正确的解决方案

标签: reactjs firebase react-native firebase-authentication react-navigation


【解决方案1】:

updateCurrentUser 未触发 onAuthStateChanged

Reference

因此我们需要在更新后重新加载/强制更新当前用户

firebase.auth().currentUser.reload()

firebase.auth().currentUser.getIdToken(true)

喜欢这个

state = { email: '', password: '', userName: '', errorMessage: null }

  handleSignUp = () => {     
    firebase.auth().createUserWithEmailAndPassword(this.state.email, this.state.password).then((userInfo) =>{ 
        userInfo.user.updateProfile({displayName: this.state.userName}).then(firebase.auth().currentUser.reload()).then((s) => {this.props.navigation.navigate('Navigator')})
    })
      .catch(error => this.setState({ errorMessage: error.message }))
  }

【讨论】:

  • 我在下一个屏幕上仍然得到 null useEffect(()=>{ console.log(firebase.auth().currentUser.displayName)})
  • 在获取当前用户之前可以重新加载测试吗?
  • 你说的对不起是什么意思?
  • firebase.auth().currentUser.reload() 在获取当前用户之前调用这个函数
  • firebase.auth().currentUser.reload().then(()=>{ console.log(firebase.auth().currentUser.displayName) })
【解决方案2】:

也许你需要像这样改变你的方法:

handleSignUp = async () => {     
  const userInfo = await firebase.auth().createUserWithEmailAndPassword(this.state.email, this.state.password)
  await userInfo.user.updateProfile({displayName: this.state.userName})
  this.props.navigation.navigate('Navigator')
}

【讨论】:

  • 感谢您的帮助!我会尽快检查并通知您。
  • 它仍然有同样的效果。只有在软刷新后,我才会填充 displayName
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-26
  • 2021-11-27
  • 2017-01-03
  • 1970-01-01
  • 2022-07-30
相关资源
最近更新 更多