【问题标题】:Unable to use variables inside promise无法在承诺中使用变量
【发布时间】:2019-11-05 04:25:11
【问题描述】:

我正在尝试将图片上传到 Firebase 存储,这没问题。

但是,当我尝试使用图像 URL 和从表单获取的其他一些内容来设置状态时,我的变量(部分和价格)在承诺中为空。在我的代码下面:

    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')
    }
    }

我的错误在哪里?谢谢!

【问题讨论】:

  • 你能告诉你在这里遇到什么样的错误吗?
  • 当我尝试设置状态,部分和价格为空时,它只设置带有downloadURL的图像

标签: javascript reactjs promise firebase-storage


【解决方案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')
    }
}

【讨论】:

  • 您好,感谢您的回答,当我尝试这样做时,由于某种原因它无法清除表单。
  • 别管Sathak,我没有把它放在你建议的地方,它现在可以工作了,谢谢你的支持!
猜你喜欢
  • 2017-06-07
  • 1970-01-01
  • 1970-01-01
  • 2018-02-26
  • 2016-09-18
  • 2017-10-09
  • 1970-01-01
  • 1970-01-01
  • 2020-02-18
相关资源
最近更新 更多