Reactjs react Hook功能组件中的复选框状态未更新
我在使用react钩子更新复选框状态时遇到问题, 默认情况下,复选框为false 下面是代码示例Reactjs react Hook功能组件中的复选框状态未更新,reactjs,react-hooks,Reactjs,React Hooks,我在使用react钩子更新复选框状态时遇到问题, 默认情况下,复选框为false 下面是代码示例 function GPSPosition() { const [isEnable, setCheckBoxEnable] = useState(false) const enableStopSendingData = (e) => { e.preventDefault(); setCheckBoxEnable(e.target.checked
function GPSPosition() {
const [isEnable, setCheckBoxEnable] = useState(false)
const enableStopSendingData = (e) => {
e.preventDefault();
setCheckBoxEnable(e.target.checked)
console.log(e.target.checked);// on check of CheckBox, here value is `true`
console.log(isEnable); // true is not set to isEnable, value here is `false`
}
return (
<div className="text-ellipsis">{GpsConstants.WIDGET_NAME}</div>
<Checkbox checked={isEnable} onChange={(checked) => enableStopSendingData(checked)}
className="homepage-widget-checkbox text-ellipsis" >{HomepageConst.CHECKBOX_HEADER}
</Checkbox>
</div>
)
}
函数GPSPosition(){
常量[isEnable,setCheckBoxEnable]=useState(false)
const enableStopSendingData=(e)=>{
e、 预防默认值();
setCheckBoxEnable(例如,target.checked)
console.log(e.target.checked);//选中复选框时,此处的值为'true'`
console.log(isEnable);//true未设置为isEnable,此处的值为'false'`
}
返回(
{GpsConstants.WIDGET_NAME}
启用StopSendingData(已选中)}
className=“主页小部件复选框文本省略号”>{HomepageConst.checkbox\u HEADER}
)
}
感谢快速帮助。
setCheckBoxEnable
是一种异步方法,因此您无法在setCheckBoxEnable()
之后立即获得isEnable
的更新值
您应该使用useffect
和添加isEnable
依赖项来检查更新的状态值
useEffect(() => {
console.log(isEnable);
}, [isEnable]);
setCheckBoxEnable
是一种异步方法,因此您无法在setCheckBoxEnable()
之后立即获取isEnable
的更新值
您应该使用useffect
和添加isEnable
依赖项来检查更新的状态值
useEffect(() => {
console.log(isEnable);
}, [isEnable]);
从您的代码看来,复选框应该可以正常工作,但若在设置为状态后需要更新值,则可以使用useEffect
useEffect(() => {
// Here you will get latest value
}, [stateVeriable]);
从您的代码看来,复选框应该可以正常工作,但若在设置为状态后需要更新值,则可以使用useEffect
useEffect(() => {
// Here you will get latest value
}, [stateVeriable]);
删除此行:
e.preventDefault()代码>
请参考删除这一行:e.preventDefault()代码>
参考即使删除了这一行,它也不起作用,William的上述回答有效即使删除了这一行,它也不起作用,William的上述回答有效谢谢,它有效谢谢,它有效谢谢