Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/google-cloud-platform/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs react Hook功能组件中的复选框状态未更新_Reactjs_React Hooks - Fatal编程技术网

Reactjs react Hook功能组件中的复选框状态未更新

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

我在使用react钩子更新复选框状态时遇到问题, 默认情况下,复选框为false

下面是代码示例

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的上述回答有效谢谢,它有效谢谢,它有效谢谢