[英]React Native If Statement Not Functioning properly with State
I have created this function in react native:我在本机反应中创建了这个 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")
}
}
Although the function console logs both this.state.otpEntry
and this.state.sixDigitauth
and the text in them matches, I still end up getting a console log of "incorrect OTP".尽管 function 控制台同时记录了this.state.otpEntry
和this.state.sixDigitauth
并且控制台日志中的文本“在正确的 OTP 中匹配,我仍然”。 This means that the if statement is unable to match both states.这意味着 if 语句无法匹配这两种状态。 464042 464042 incorrect OTP
Both data types are text: this.state = { sixDigitauth: '', otpEntry: '', }
两种数据类型都是文本: this.state = { sixDigitauth: '', otpEntry: '', }
Any idea why?知道为什么吗?
thanks in advance提前致谢
It appears like you have a mismatch of datatypes, and since a triple equal
sign attempts to match variables on their content, as well as their type - it returns false
, hence your query fails.看起来您的数据类型不匹配,并且由于triple equal
等号尝试匹配其内容上的变量以及它们的类型 - 它返回false
,因此您的查询失败。
You have a couple of options:你有几个选择:
+
sign in front of the variables.在变量前面添加一个+
号。 It will convert them to a Number
type:它将它们转换为Number
类型: confirmOTP(){
if (+this.state.otpEntry === +this.state.sixDigitauth) {
// do something
} else {
// do something else
}
}
===
sign, with ==
sign.将===
符号替换为==
符号。 I don't recommend it, but it will technically solve the problem.我不推荐它,但它会在技术上解决问题。 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
}
}
Make sure to catch up on some theory.确保赶上一些理论。
equations: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness方程: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness
unary plus: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Unary_plus一元加: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Unary_plus
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.