javascript - How to toggle checkbox value in React Hooks? - Stack Overflow

I have an input type checkbox as follow:const [is_checked,set_is_checked]= useState(false);const toggle

I have an input type checkbox as follow:

const [is_checked,set_is_checked]= useState(false);

const toggle_payment = () => {
    set_is_checked(!is_checked);
    console.log(is_checked);
}


return(
    <div>
        <input checked={is_checked}  onChange={toggle_value} type="checkbox"/>
    </div>
)

The problem

This seems to work fine, But when I console.log(is_checked) it looks like it prints the previous value. I tried both onChange and onClick but got the same result. What confuses me is that the checkbox is getting checked / unchecked each time I click on the box, but the console.log prints different value than what expected to print, like when I check the box with the mouse click, the box got checked but the console.log prints false

I have an input type checkbox as follow:

const [is_checked,set_is_checked]= useState(false);

const toggle_payment = () => {
    set_is_checked(!is_checked);
    console.log(is_checked);
}


return(
    <div>
        <input checked={is_checked}  onChange={toggle_value} type="checkbox"/>
    </div>
)

The problem

This seems to work fine, But when I console.log(is_checked) it looks like it prints the previous value. I tried both onChange and onClick but got the same result. What confuses me is that the checkbox is getting checked / unchecked each time I click on the box, but the console.log prints different value than what expected to print, like when I check the box with the mouse click, the box got checked but the console.log prints false

Share Improve this question edited Apr 25, 2020 at 23:36 Ali asked Apr 25, 2020 at 23:28 AliAli 1,7599 gold badges42 silver badges70 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

the state update using the updater provided by useState hook is asynchronous, and will not immediately reflect and update but will trigger a re-render

i think that if you console.log() outside the function you might gonna see the changes of the is_checked

This is due to the way state management works in React. A call to a state setter function (in this case set_is_checked) will update the value, but that updated value is available on the next render. When you call console.log below set_is_checked, you are still referencing the old value prior to the state being set.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745301165a4621442.html

相关推荐

  • javascript - How to toggle checkbox value in React Hooks? - Stack Overflow

    I have an input type checkbox as follow:const [is_checked,set_is_checked]= useState(false);const toggle

    8小时前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信