我正在尝试将图片上传到Firebase存储,没问题。
但是,当我尝试使用图像URL以及从表单中获取的其他一些东西来设置状态时,我的变量(节和价格)在promise中为空。在我的代码下面:
handleForm = e =>{
e.preventDefault();
const {section, price, image} = e.target
const file = image.files[0]
const pictureName = userInformation.name.replace(/ /g, "_");
if(file.size <= 1000000){
const myRoute = '/img/userPictures/' + pictureName;
const storageRef = firebase.storage().ref(myRoute);
const task = storageRef.put(file);
task.on('state_changed', snapshot =>{
console.log('Uploaded');
}, error =>{
console.log(error.message)
}, () =>{
task.snapshot.ref.getDownloadURL().then(downloadURL =>{
this.setState({
information: this.state.data.concat([{
section: section.value,
price: price.value,
image:downloadURL}])
})
});
})
e.currentTarget.reset();
this.notifySuccess('Information uploaded');
}else{
this.notifyError('Image should be less than 1 MB')
}
}
我在哪里出现错误?谢谢!
答案 0 :(得分:1)
这是因为您在回调之外使用e.currentTarget.reset()
。
尝试将其放入成功的回调中,它应能按预期工作
(如下图所示)
handleForm = e => {
e.preventDefault()
const {section, price, image} = e.target
const file = image.files[0]
const pictureName = userInformation.name.replace(/ /g, '_')
if (file.size <= 1000000) {
const myRoute = '/img/userPictures/' + pictureName
const storageRef = firebase.storage().ref(myRoute)
const task = storageRef.put(file)
task.on(
'state_changed',
snapshot => {
console.log('Uploaded')
},
error => {
console.log(error.message)
},
() => {
task.snapshot.ref.getDownloadURL().then(downloadURL => {
this.setState({
information: this.state.data.concat([
{
section: section.value,
price: price.value,
image: downloadURL
}
])
})
})
e.currentTarget.reset()
this.notifySuccess('Information uploaded')
}
)
} else {
this.notifyError('Image should be less than 1 MB')
}
}