我正在尝试使用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)
});
}