javascript - Firebase / React:onAuthStateChanged()是在注册功能之前还是之后触发的?
问题描述
好吧,伙计们,这真的很奇怪。
我有一个App
班级和一个SignInWithPassword
班级。只要没有用户登录,SignInWithPassword
就会呈现出来。我有一个表单,用户可以在其中输入他们选择的用户名、电子邮件和密码,然后注册。App
我user
在 App 的状态中有一个对象,该对象设置在onAuthStateChanged
. 我一直面临设置 displayName 的问题,App.state.user.displayName
因为当您仅使用电子邮件和密码登录时,firebase 的默认user.displayName
设置为null
. 我尝试使用updateProfile
但仍然没有设置App
's user.displayName
,它只更新了 firebase 的user
对象,并且 updateProfile 不会触发 onAuthStateChanged。那么,我想我会尝试在里面创建一个 setDisplayName 方法App
,将它作为道具传递给SignInWithPassword
,then
. 但这仍然不会改变,App.user.displayName
除非我刷新它。在进行一些日志记录后,我注意到了一些奇怪的事情。
我有 3console.log()
秒。一种 insideSignInWithPassword
的signUp
方法:
signUp = () => {
firebase.auth().createUserWithEmailAndPassword(this.state.email, this.state.password).then(() => {
console.log(firebase.auth().currentUser) //log 1
firebase.auth().currentUser.updateProfile({
displayName: this.state.username,
})
this.props.setUsername(this.state.username)
}).catch((error) => {
// Handle Errors here.
alert(error.message)
this.setState({
email: '',
password: '',
})
})
}
一个在里面onAuthStateChanged
,App
firebase.auth().onAuthStateChanged((user) => {
if (user) {
console.log(user.displayName) //log 2
const currentUser = {
displayName: user.displayName,
email: user.email,
uid: user.uid,
}
this.setState({
user: currentUser,
})
} else {
this.setState({
user: {}
})
}
})
}
和一个 insideApp
的setUsername()
方法:
setUsername = (username) => {
const user = Object.assign({}, this.state.user)
user.displayName = username
this.setState({
user,
})
console.log(this.state.user.displayName) //log 3
}
显示日志的顺序是日志 1、日志 3、日志 2。这显然意味着 onAuthStateChanged 仅then
在signUp
. 这意味着log 2
应该打印用户在表单中输入的用户名,对吗?错误的。它打印null
。有人可以解释发生了什么吗??
解决方案
几个小时前我遇到了这个问题,我改变了
firebase.auth().currentUser.updateProfile({
和
auth.doCreateUserWithEmailAndPassword(email, passwordOne)
.then(authUser => {
this.setState(() => ({ ...INITIAL_STATE }));
authUser.user.updateProfile({
displayName: firstName + " "+lastName
})
它以这种方式对我有用,而不是 .currentUser
推荐阅读
- c++ - std::string 添加到 char*
- sql - sql 中这种 case 表达式的一种更简洁的方法
- laravel - Laravel 5.5 和 DB::raw 无法执行查询
- c# - 是否有一个属性可以为每个函数添加正确的响应类型属性
- postgresql - 选择持续时间段的模式
- android - GPUMp4Composer 应用过滤器
- powerbi - 如何仅选择每个表格视觉对象中的一项
- mysql - 将特定列存储和检索到包含存储过程中单行的结果集的变量中
- java - 为什么我在控制器中收到来自邮递员请求的空值?
- android - 如何将带有invokeMethod的字符串数组从Native传递到flutter