Javascript 使用带有firebase身份验证的updateProfile时,displayName会被修剪
我使用firebase authentication createUserWithEmailAndPassword创建用户,并使用updateProfile方法更新用户的显示名。下面是我的代码Javascript 使用带有firebase身份验证的updateProfile时,displayName会被修剪,javascript,reactjs,firebase,authentication,firebase-authentication,Javascript,Reactjs,Firebase,Authentication,Firebase Authentication,我使用firebase authentication createUserWithEmailAndPassword创建用户,并使用updateProfile方法更新用户的显示名。下面是我的代码 const signUp = (event) => { event.preventDefault(); console.log(username); auth.createUserWithEmailAndPassword(email,password) .th
const signUp = (event) => {
event.preventDefault();
console.log(username);
auth.createUserWithEmailAndPassword(email,password)
.then((authUser)=>{
authUser.user.updateProfile({
displayName : username
})
})
.catch(err=>alert(err.message));
}
用户单击注册按钮时,将触发注册功能。用户名在控制台中正确显示。
创建用户后,还有另一个useEffect钩子将authUser记录到控制台
useEffect(()=>{
const unsubscribe = auth.onAuthStateChanged((authUser)=>{
if(authUser){
//user has login...
console.log(authUser);
setUser(authUser);
if(authUser.displayName){
//dont update username
}else{
return authUser.updateProfile({
displayName : username,
})
}
}else{
//user has logged out...
setUser(null);
}
return () => {
//perform some cleanup actions
unsubscribe();
}
})
},[user,username])
除了displayName被修剪外,auth用户的属性似乎显示得很好。(这个“测试”应该是“测试”)
调用
updateProfile
不会对身份验证状态观测器的工作方式造成任何更改。事实上,如果删除对updateProfile
的调用,我确信日志将完全相同onAuthStateChanged
将接收通过调用createUserWithEmailAndPassword
创建的初始用户对象。也许您看到的是一个初始的displayName
值,它只包含电子邮件地址中“@gmail.com”之前的所有内容
如果调用
updateProfile
,并且希望观察displayName中的更改,则应注销用户并重新登录以获取新的用户对象。或者,更好的是,您可以将显示名称存储在数据库中,以便可以立即读取和写入它。我想问题是因为updateProfile是异步的。在我将回调函数转换为异步函数后,displayName不再被修剪
const signUp = (event) => {
event.preventDefault();
console.log(username);
auth.createUserWithEmailAndPassword(email, password)
.then(async (authUser) => {
await authUser.user.updateProfile({
displayName: username,
})
})
.catch(err => alert(err.message));
setOpen(false);
}
我尝试注销并登录用户,但displayName仍然是修剪后的displayName。而且,displayName没有按照特定的模式进行裁剪,有时它会将“海绵宝宝”裁剪为“sb”,“本”裁剪为“B”,这真的很奇怪。