React集成Firebase Auth:注册后无法实时获取displayName求助
解决Firebase Auth注册后无法实时获取displayName的问题
问题原因
createUserWithEmailAndPassword和updateProfile均为异步操作,原代码未等待updateProfile执行完成就清空表单,且onAuthStateChanged仅在组件挂载时触发一次,用户属性更新后不会自动触发重新渲染。- 注册成功后用户已处于登录状态,
updateProfile仅修改用户属性,不会触发onAuthStateChanged回调,因此currentUser状态不会自动同步新的displayName。
修改后的代码
const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const [name, setName] = useState(""); const [currentUser, setCurrentUser] = useState({}); const [error, setError] = useState({}); const handleSubmit = async (e) => { e.preventDefault(); try { // 完成用户创建并获取用户实例 const userCredential = await createUserWithEmailAndPassword(auth, email, password); const user = userCredential.user; // 等待displayName更新操作完成 await updateProfile(user, { displayName: name, }); // 手动更新当前用户状态,实时显示displayName setCurrentUser({...user, displayName: name}); // 清空表单 setName(""); setEmail(""); setPassword(""); } catch (err) { setError(new Error("Sorry !! Couldn't find user !!")); } }; useEffect(() => { const unsubscribe = onAuthStateChanged(auth, (user) => { setCurrentUser(user); }); // 清理监听,避免内存泄漏 return () => unsubscribe(); }, []);
修改说明
- 改用
async/await处理异步操作,确保updateProfile执行完成后再更新状态,避免竞态问题。 - 从
createUserWithEmailAndPassword的返回值中获取用户实例,替代直接使用auth.currentUser,提升可靠性。 - 在
updateProfile完成后手动更新currentUser状态,同步新的displayName,实现实时显示。 - 给
useEffect添加清理函数,取消auth状态监听,防止组件卸载后出现内存泄漏。
内容的提问来源于stack exchange,提问作者Sumon Chandra
相关产品推荐
相关产品推荐

