簡體   English   中英

使用 State 反應原生 If 語句無法正常運行

[英]React Native If Statement Not Functioning properly with State

我在本機反應中創建了這個 function:

confirmOTP(){
  console.log(this.state.otpEntry)
  console.log(this.state.sixDigitauth)
  if (this.state.otpEntry === this.state.sixDigitauth){
    this.setState({
      modalVisibility: false
    })
    console.log ("authenticated")
  }else{
    console.log ("incorrect OTP")
  }
}

盡管 function 控制台同時記錄了this.state.otpEntrythis.state.sixDigitauth並且控制台日志中的文本“在正確的 OTP 中匹配,我仍然”。 這意味着 if 語句無法匹配這兩種狀態。 464042 464042 incorrect OTP

兩種數據類型都是文本: this.state = { sixDigitauth: '', otpEntry: '', }

知道為什么嗎?

提前致謝

看起來您的數據類型不匹配,並且由於triple equal等號嘗試匹配其內容上的變量以及它們的類型 - 它返回false ,因此您的查詢失敗。

你有幾個選擇:

  1. 在變量前面添加一個+號。 它將它們轉換為Number類型:
  confirmOTP(){
    if (+this.state.otpEntry === +this.state.sixDigitauth) {
      // do something
    } else {
      // do something else
    }
  }
  1. ===符號替換為==符號。 我不推薦它,但它會在技術上解決問題。
  confirmOTP(){
    if (this.state.otpEntry == this.state.sixDigitauth) {
      // do something
    } else {
      // do something else
    }
  }
  1. 在更新 state 時,您還可以確保它們處於適當的數據類型中:
  constructor(props) {
    super(props)
    this.state = {
      otpEntry: +props.otpEntry
      sixDigitauth: +props.sixDigitauth
    }
  }

確保趕上一些理論。

方程: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness

一元加: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Unary_plus

暫無
暫無

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

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