简体   繁体   English

使用 State 反应原生 If 语句无法正常运行

[英]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.otpEntrythis.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:你有几个选择:

  1. Add a + 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
    }
  }
  1. Replace a === 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
    }
  }
  1. You could also make sure they're in appropriate datatypes, at the moment of updating the state:在更新 state 时,您还可以确保它们处于适当的数据类型中:
  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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM