簡體   English   中英

在將數據推送到數據庫之前,如何確保 if 函數運行?

[英]How do I make sure my if funtion runs before my data is pushed to a database?

嗨,這兩行代碼運行並完美地執行(用控制台日志測試)但由於某種原因,數據似乎在 this.state.weight 除以 2.2 之前被推送到數據庫中,有誰知道我為什么嘗試 .then聲明,但會導致編譯錯誤,修復是什么,提前致謝! :)

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



    }

由於 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!')
  }
}

您需要在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;
}

反應 setState() 文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM