React+Redux+Firebase文件上传:如何将图片URL存入pictureUrl state?
解决Firebase上传后无法将Download URL存入React State的问题
嘿,我明白你现在遇到的问题了——这本质上是异步操作的顺序问题。你现在的代码里,uploadImage是一个异步函数(因为Firebase的文件上传和获取下载链接都是基于Promise的异步操作),但你调用它之后立刻就去构建article对象并执行saveArticle了,这时候下载链接还没拿到呢!而且你的uploadImage函数也没有把获取到的downloadURL传递回组件,自然没法更新pictureUrl状态。
下面分两步帮你搞定这个问题:
第一步:修改uploadImage函数,让它返回包含Download URL的Promise
我们需要让uploadImage完成上传并获取到下载链接后,把这个链接返回给调用它的组件:
export function uploadImage(picture){ return dispatch => { // 返回整个Promise链,让组件能拿到最终的下载链接 return storage.child('/images/' + picture.name).put(picture).then((snapshot) => { return snapshot.ref.getDownloadURL(); // 返回获取下载链接的Promise }).then(downloadURL => { console.log('File available at: ', downloadURL); return downloadURL; // 把下载链接传递出去 }); } }
第二步:修改组件的handleSubmit函数,等待上传完成后再处理
因为uploadImage现在返回了Promise,我们可以把handleSubmit改成异步函数,用await等待上传完成并拿到下载链接,再把它赋值给pictureUrl,然后构建article对象:
async handleSubmit(e){ e.preventDefault(); console.log(this.state.picture); // 等待上传完成,拿到下载链接 const pictureUrl = await this.props.uploadImage(this.state.picture); const article = { header: this.state.header, tagLine: this.state.tagLine, articleType: this.state.articleType, system: this.state.system, body: this.state.body, pictureUrl: pictureUrl // 这里填入拿到的下载链接 } this.props.saveArticle(article); console.log('Data saved!'); // 重置状态 this.setState({ header: '', tagLine: '', articleType: '', system: '', body: '', pictureUrl: '' }) }
额外提示:给代码加个错误处理
为了让你的代码更健壮,建议用try/catch包裹异步操作,避免上传或保存出错时导致页面崩溃:
async handleSubmit(e){ e.preventDefault(); try { console.log(this.state.picture); const pictureUrl = await this.props.uploadImage(this.state.picture); const article = { header: this.state.header, tagLine: this.state.tagLine, articleType: this.state.articleType, system: this.state.system, body: this.state.body, pictureUrl: pictureUrl } this.props.saveArticle(article); console.log('Data saved!'); this.setState({ header: '', tagLine: '', articleType: '', system: '', body: '', pictureUrl: '' }) } catch (error) { console.error('上传或保存出错:', error); // 这里可以添加用户可见的错误提示,比如弹出提示框 } }
这样修改后,就能保证你在拿到下载链接之后再去创建并保存文章,pictureUrl自然就能正确赋值啦!
内容的提问来源于stack exchange,提问作者Chris Simmons
相关产品推荐
相关产品推荐

