Firebase displayName在第一次渲染时返回null


  • 我有一个对象userInfo具有字段displayName(第17行(,但userInfo.displayName为null??(第18行(
  • 重新加载页面将解决问题(有价值((可能是因为依赖关系是位置和导航(
  • 我想可能是因为我得到了数据,而Firebase还没有更新displayName
  • 有人有解决方案吗?非常感谢

我正在使用firebase进行注册。但是Firebase只允许使用电子邮件和密码注册(不包括displayName(,所以我必须手动更新displayName

Auth Provider.jsx

function AuthProvider({children}) {
const [user, setUser] = React.useState({})
const navigate = useNavigate();
const location = useLocation();
React.useEffect(() => {
const unSubscribe = onAuthStateChanged(auth,  (userInfo) => {
if(userInfo) {
console.log(userInfo); // line 17 => have value
console.log(userInfo.displayName); // line 18 => null
const { displayName, email, photoURL, uid } = userInfo;
setUser({ displayName, email, photoURL, uid })
if(location.pathname !== "/profile") navigate("/chat-room")
return;
}
// reset user info
setUser({});
navigate("/home")
})

return () => {
unSubscribe()
}

},[navigate, location.pathname, ])
console.log(user)
return (
<AuthContext.Provider value={{user}}>
{children}
</AuthContext.Provider>
);

处理Signup.jsx

const onFinish = async (values) => {
if (mode === "sign-up") {
try {
console.log(values)
const { user } = await createUserWithEmailAndPassword(
auth,
values.email,
values.password
);
await updateProfile(auth.currentUser, { 
displayName: values.displayName,
})

您对Firebase API进行两个单独的调用:

  1. 首先调用createUserWithEmailAndPassword来创建用户配置文件
  2. 然后调用updateProfile来设置用户的显示名称

第一个调用创建用户配置文件并将其登录,从而触发onAuthStateChanged。由于第二个调用还没有发生,因此处理程序确实会看到当时没有显示名称的用户配置文件。

从重新加载页面中可以看到,显示名称最终会显示出来。同样,当Firebase自动刷新配置文件时,它也会在一个小时后显示。另一个选项是在设置显示配置文件后调用getAuth().currentUser.reload(),这也将强制更新配置文件。

当我们调用updateProfile函数并更新displayName时,onAuthStateChanged不会被触发。解决方案是您必须在手动更新displayNamewith a different object后设置用户。

const { user } = await createUserWithEmailAndPassword(
auth,
values.email,
values.password
);
await updateProfile(auth.currentUser, { 
displayName: values.displayName,
}) 
// update `user` state
setUser({...user});

现在问题应该解决了。

最新更新