Как убедиться, что функция if выполняется до того, как мои данные будут отправлены в базу данных? - PullRequest
1 голос
/ 29 марта 2020

Привет, обе эти строки кода работают и отлично работают (протестировано с журналами консоли), но по какой-то причине данные, похоже, передаются в базу данных до того, как this.state.weight делится на 2.2. Кто-нибудь знает, почему я пытался .hen заявление, но это вызывает ошибку компиляции, что исправить, спасибо заранее! :)

  calculate_bmi = () => {
        if (this.state.weightUnits === 'lbs') {

            this.setState({ Weight: this.state.Weight / 2.2 });
        }

        if (this.state.Gender !== '' && this.state.Age !== '' && this.state.Height !== '' && this.state.Weight !== '' && this.state.Goal !== '') {
            database.collection('Health_data').doc(localStorage.getItem('user')).set({
                gender: this.state.Gender,
                age: this.state.Age,
                height: this.state.Height,
                weight: this.state.Weight,
                goal: this.state.Goal
            }).catch((error) => {
                alert(error.message)
                console.log('failed to write', error);
            });
        } else {
            alert('Please fill in all fields so we can get you started on your fitness journey!')
        }



    }

Ответы [ 2 ]

2 голосов
/ 29 марта 2020

Вам нужно запустить проверку обновлений БД после того, как вы setState(), вы можете сделать это, используя обратный вызов, предоставленный в качестве второго аргумента для setState(). Кроме того, вы можете извлечь выгоду из условия обновления вашей БД + вызова функции.

Пример:

calculate_bmi = () => { 
  // This comparison also feels unsafe, can the person accidentally save twice and divide the now kilogram weight again by 2.2?
  if (this.state.weightUnits === 'lbs') {
      this.setState(
        { Weight: this.state.Weight / 2.2 }, 
        // Callback performed AFTER the state gets updated
        () => this.saveData()
      );
  } else {
    this.saveData();  
  }
}

saveData = () => {
    if (
        this.state.Gender !== '' && 
        this.state.Age !== '' && 
        this.state.Height !== '' && 
        this.state.Weight !== '' && 
        this.state.Goal !== ''
    ) {
      database.collection('Health_data').doc(localStorage.getItem('user')).set({
          gender: this.state.Gender,
          age: this.state.Age,
          height: this.state.Height,
          weight: this.state.Weight,
          goal: this.state.Goal
      }).catch((error) => {
          alert(error.message)
          console.log('failed to write', error);
          return false;
      });
  } else {
      alert('Please fill in all fields so we can get you started on your fitness journey!');
      return false;
  }

  return true;
}

React setState () docs

2 голосов
/ 29 марта 2020

Вызвано тем, что React запустит функцию setState, но не будет ждать результата и выполнит следующие строки. Поэтому, пока ваше состояние обновляется, будет запущен ваш второй оператор if без правильных данных.

calculate_bmi = () => {
  let weight = this.state.Weight;
  if (this.state.weightUnits === 'lbs') {
      weight /= 2.2;
      this.setState({ Weight: weight });
  }

  if (this.state.Gender !== '' && this.state.Age !== '' && this.state.Height !== '' && this.state.Weight !== '' && this.state.Goal !== '') {
      database.collection('Health_data').doc(localStorage.getItem('user')).set({
          gender: this.state.Gender,
          age: this.state.Age,
          height: this.state.Height,
          weight: weight, // change the variable you are sending
          goal: this.state.Goal
      }).catch((error) => {
          alert(error.message)
          console.log('failed to write', error);
      });
  } else {
      alert('Please fill in all fields so we can get you started on your fitness journey!')
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...