Firebase选择头像时报updateProfile is not a function错误如何解决
错误根源
- 方法调用错误:
updateProfile是已登录用户实例的方法,不能直接通过firebase.auth()调用 - 头像组件未绑定动态路径:当前Avatar的src写死为本地静态资源,不会随上传结果更新
修复方案
1. 修正文件上传处理函数
调整 handleFileInputChange 中更新用户资料的逻辑,增加用户登录状态判空,避免空指针报错:
async function handleFileInputChange(e) { const files = e.target.files; const file = files[0]; if (!file) return; const storage = firebase.storage(); const usersImageRef = storage .ref() .child(`users/${user.uid}/profilepicture.jpg`); const snap = await usersImageRef.put(file); const downloadURL = await snap.ref.getDownloadURL(); setDownloadURL(downloadURL); // 修正调用逻辑,从当前登录用户实例调用updateProfile const currentUser = firebase.auth().currentUser; if (currentUser) { await currentUser.updateProfile({ photoURL: downloadURL }); } }
2. 修正头像组件的src绑定
将Avatar的src改为优先读取状态中存储的下载链接,没有值时 fallback 到默认头像,同时补全label的关联属性,实现点击头像直接触发文件选择的交互优化:
<input accept="image/*" className={classes.input} id="contained-button-file" multiple type="file" onChange={handleFileInputChange} /> <label htmlFor="contained-button-file"> <IconButton component="span"> <Avatar src={downloadURL || "../assets/ana.png"} style={{ margin: "10px", width: "60px", height: "60px", }} /> </IconButton> </label>
内容的提问来源于stack exchange,提问作者chin14
相关产品推荐
相关产品推荐

