无法在Promise中使用变量

凯文·梅伦德斯(Kevin Melendez)

我正在尝试将图片上传到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')
    }
    }

我在哪里有错误?谢谢!

萨尔塔克

这是因为您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')
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章