[英]Can't understand why I can't access the value of counter
Why does the conditional statement inside handleDecrement
if(counter>1)
not work?为什么
handleDecrement
if(counter>1)
中的条件语句不起作用?
const [counter, setCounter] = React.useState(1);
function handleIncrement (counter){
setCounter(counter => counter + 1)
}
function handleDecrement (counter){
if(counter>1){
setCounter(counter => counter - 1)
}
}
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. 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) } }
And then attaching it to onClick event:然后将其附加到 onClick 事件:
<Button onClick={() => handleIncrement(counter)}> <Button onClick={() => handleDecrement(counter)}>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.