[英]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.otpEntry
和this.state.sixDigitauth
並且控制台日志中的文本“在正確的 OTP 中匹配,我仍然”。 這意味着 if 語句無法匹配這兩種狀態。 464042 464042 incorrect OTP
兩種數據類型都是文本: this.state = { sixDigitauth: '', otpEntry: '', }
知道為什么嗎?
提前致謝
看起來您的數據類型不匹配,並且由於triple equal
等號嘗試匹配其內容上的變量以及它們的類型 - 它返回false
,因此您的查詢失敗。
你有幾個選擇:
+
號。 它將它們轉換為Number
類型: confirmOTP(){
if (+this.state.otpEntry === +this.state.sixDigitauth) {
// do something
} else {
// do something else
}
}
===
符號替換為==
符號。 我不推薦它,但它會在技術上解決問題。 confirmOTP(){
if (this.state.otpEntry == this.state.sixDigitauth) {
// do something
} else {
// do something else
}
}
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.