【发布时间】:2021-04-23 21:06:32
【问题描述】:
我在 react native 中创建了这个函数:
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")
}
}
虽然函数控制台记录了this.state.otpEntry 和this.state.sixDigitauth 并且它们中的文本匹配,但我最终还是得到了“不正确的OTP”的控制台日志。这意味着 if 语句无法匹配这两种状态。
464042 464042 incorrect OTP
两种数据类型都是文本:
this.state = { sixDigitauth: '', otpEntry: '', }
知道为什么吗?
提前致谢
【问题讨论】:
-
从他们的名字来看,我怀疑他们应该是数字。你确定它们都是相同的数据类型吗?
-
可能是数据类型或空白修剪的问题
-
@kerimErkan 你能在你的 if 语句上方添加这一行,让我们知道它说的是什么吗?
console.log({ otpEntry: typeof this.state.otpEntry, sixDigitauth: typeof this.state.sixDigitauth })-- 这将让我们确定这些值是什么数据类型。它们可以是字符串或数字,它们看起来可能相同,但它们不是===。 -
this.state.otpEntry.trim() === this.state.sixDigitAuth.trim()
-
@ShadabSiddiqui 它不起作用。三等式检查数据类型,因此除非它们都是字符串 - 检查将失败。另外,Number 没有 trimp 方法,所以它也会在那里失败。 @kerim Erikan 如果两个值都是字符串/数字类型,您可以在它们前面放置一个
+符号,这会将它们转换为数字并消除任何潜在的空格。
标签: javascript node.js reactjs