Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Why does the conditional statement inside handleDecrement if(counter>1) not work?

const [counter, setCounter] = React.useState(1);

function handleIncrement (counter){
  setCounter(counter => counter + 1)
}
function handleDecrement (counter){
  if(counter>1){
    setCounter(counter => counter - 1)
  }
}
question from:https://stackoverflow.com/questions/65843995/cant-understand-why-i-cant-access-the-value-of-counter

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
196 views
Welcome To Ask or Share your Answers For Others

1 Answer

You're not calling these function inside setCounter, you're just passing arrow function definitions and not the calculated value of the counter, so then inside the if statement, you're comparing not the integer with integer, but a function definition with an integer.

Fixed code:

const [counter, setCounter] = React.useState(1);

function handleIncrement(counterArg) {
  setCounter(counterArg + 1)
}

function handleDecrement(counterArg) {
  if (counterArg > 1) {
    setCounter(counterArg - 1)
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...