Невозможно использовать переменные внутри обещания - PullRequest
1 голос
/ 22 июня 2019

Я пытаюсь загрузить картинку в хранилище 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')
    }
    }

Где у меня ошибка? спасибо!

1 Ответ

1 голос
/ 22 июня 2019

Это потому, что вы используете 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')
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...