如何解决getDownloadURL在reactjs中不起作用
我正在尝试使用Firebase存储进行图像上传。图像已成功添加到图像文件夹下的存储中。 但是我无法从当前状态的getDownloadUrl()获取该URL,当前URL的状态已初始化为先前URL的值。 我发现可能存在异步问题,因此也使用了异步和等待。 这是我的代码: 我已经将所有方法绑定到构造函数中。
//for image
handleChange1 = e => {
if (e.target.files[0]) {
const image = e.target.files[0];
this.setState(() => ({ image }));
}
};
// for textfields
handleChange = (e)=>{
this.setState({
[e.target.id] :e.target.value
})
console.log(e.target.id)
}
//handle onSubmit()
handleSubmit= async (e)=>{
e.preventDefault();
//checks whether image is there
if(this.state.image){
const { image } = this.state;
// adding image to the images folder of storage
const uploadTask = await firebase.storage().ref(`images/${image.name}`)
.put(image).on(
"state_changed",snapshot => {
},error => {
// Error function ...
console.log("Error from firebase storage",error);
},() => {
// complete function ...
firebase.storage()
.ref("images")
.child(image.name)
.getDownloadURL() // <- this is not working
.then(url => {
this.setState(() => ({ url }));
}).catch(
err =>{
console.log("something went wrong while getting URL",err)
}
);
}
)
}
// adding all the data to the firestore
const db= await firebase.firestore()
db.collection("newsData").add({
heading : this.state.heading,link:this.state.link,date:this.state.date,description:this.state.description,url:this.state.url ? this.state.url : null,// image:this.state.image ?this.state.image :null
}).finally(( res)=>{
console.log("Succefully added news",res)
})
.catch((err) => {
console.log("error occured",err)
});
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。