首页 > 解决方案 > 复选框状态未在反应钩子功能组件中更新

问题描述

我在使用反应钩子更新复选框状态时遇到问题,默认复选框为假,

下面的代码示例

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>
   )
}

感谢快速帮助。

标签: reactjsreact-hooks

解决方案


setCheckBoxEnable是异步方法,因此您无法isEnable立即获取 after的更新值setCheckBoxEnable()

        setCheckBoxEnable(e.target.checked) 
        console.log(isEnable); // This will show old value of `isEnable`

您应该使用useEffectwith 添加isEnable依赖项来检查更新的状态值。

useEffect(() => {
  console.log(isEnable);
}, [isEnable]);

推荐阅读