reactjs - 复选框状态未在反应钩子功能组件中更新
问题描述
我在使用反应钩子更新复选框状态时遇到问题,默认复选框为假,
下面的代码示例
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>
)
}
感谢快速帮助。
解决方案
setCheckBoxEnable
是异步方法,因此您无法isEnable
立即获取 after的更新值setCheckBoxEnable()
。
setCheckBoxEnable(e.target.checked)
console.log(isEnable); // This will show old value of `isEnable`
您应该使用useEffect
with 添加isEnable
依赖项来检查更新的状态值。
useEffect(() => {
console.log(isEnable);
}, [isEnable]);
推荐阅读
- reactjs - 谷歌云存储桶上的反应托管没有这样的关键错误
- python - 此字符串替换 lambda 组函数如何工作的说明或文档
- android - Kotlin 协程从 SharedPreferences 流出并使用 GlobalScope 与 MainScope 观察存储库中的数据流
- db2 - 我需要屏蔽才能仅查看最后 4 位数字
- amazon-web-services - AWS CDK - 如何在部署之前将 Lambda 的调用权限授予 API Gateway?
- sql - 如何在不必按两个子句分组的情况下将两个表连接在一起?PostgreSQL
- reactjs - 如何在 Flux 的 calculatestate 方法中设置新状态?
- hyperledger-fabric - IBM Blockchain Platform Nodejs 客户端应用程序无法提交事务:没有为要从中发现的 MSP 'org1Admin' 定义对等方
- javascript - 导出在 React 组件的 fetch() 函数中的 then() 方法中创建的变量
- regex - RegEx.Replace 函数限制返回的字符