【问题标题】:React Native If Statement Not Functioning properly with StateReact Native If 语句在状态下无法正常运行
【发布时间】: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.otpEntrythis.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


【解决方案1】:

您的数据类型似乎不匹配,并且由于 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. 您还可以在更新状态时确保它们处于适当的数据类型中:
  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

【讨论】:

  • 选项 1(添加 + 号)完美运行。事实证明,正如您所提到的,我创建的随机数生成器是数字数据类型,而用户输入的数据是字符串。谢谢帕特里克!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-06
  • 1970-01-01
  • 1970-01-01
  • 2020-01-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多