admin管理员组文章数量:1419235
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
2 Answers
Reset to default 4the 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.
本文标签: javascriptHow to toggle checkbox value in React HooksStack Overflow
版权声明:本文标题:javascript - How to toggle checkbox value in React Hooks? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745301165a2652378.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论