简体   繁体   中英

React Native If Statement Not Functioning properly with State

I have created this function in 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")
  }
}

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". This means that the if statement is unable to match both states. 464042 464042 incorrect OTP

Both data types are text: 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.

You have a couple of options:

  1. Add a + sign in front of the variables. It will convert them to a Number type:
  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:
  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

unary plus: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Unary_plus

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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