reactjs - 使用钩子时等待状态更新
问题描述
如何使用 Hooks 等待状态更新。当我提交表单时,我需要termsValidation
在运行一些附加代码之前检查是否为假。如果状态刚刚改变,它就不会注意到这一点。
import React, { useState } from 'react';
export default function Signup() {
const [terms, setTerms] = useState('');
const [termsValidation, setTermsValidation] = useState(false);
function handleSubmit(e) {
e.preventDefault();
if (!terms) {
setTermsValidation(true);
} else {
setTermsValidation(false);
}
if (!termsValidation) {
console.log('run something here');
}
}
return (
<div>
<form>
<input type="checkbox" id="terms" name="terms" checked={terms} />
<button type="submit" onClick={handleSubmit}>
Sign up
</button>
</form>
</div>
);
}
解决方案
钩子是异步的useState
,但它没有回调 api setState
。如果你想等待状态更新,你需要一个useEffect
钩子:
import React, { useState, useEffect } from 'react';
export default function Signup() {
const [terms, setTerms] = useState('');
const [termsValidation, setTermsValidation] = useState(false);
useEffect(() => {
if (!termsValidation) {
console.log('run something here');
}
}, [termsValidation]);
function handleSubmit(e) {
e.preventDefault();
if (!terms) {
setTermsValidation(true);
} else {
setTermsValidation(false);
}
}
return (
<div>
<form>
<input type="checkbox" id="terms" name="terms" checked={terms} />
<button type="submit" onClick={handleSubmit}>
Sign up
</button>
</form>
</div>
);
}
推荐阅读
- ios - 为什么导航推送/弹出和模态呈现/关闭的视图生命周期过程在swift中不同?
- python - 逻辑回归的贝叶斯优化
- python - 参数 #2 'mat1' 的张量在 CPU 上,但预计它在 GPU 上(同时检查 addmm 的参数
- javascript - 儿童宽度计算标准?
- python - 在 python 中创建一个 DOT 文件
- node.js - 我的快速路由在不同的不和谐服务器上不起作用
- azure - Azure Devops 可以免费更改用户吗?
- android - Playstore 锁屏打开时 inappreview 触发器
- bash - 为什么 C 文件名可以在编写 bash 脚本后立即保存在变量中?
- c++ - OBS 如何将某物区分为 3rd 方覆盖?