我面临一个奇怪的情况,但不知道到底是什么问题。
我已经使用下面的代码创建了一个新的自定义表单const CustomForm = ({ status, message, onValidated }) => {
const [email, setEmail] = useState('')
const [customErr, setCustomErr] = useState(false);
const handleSubmit = (e) => {
e.preventDefault();
setEmail(e.currentTarget.email.value)
console.log(email.length)
if(email.length === 0) {
setCustomErr(true);
return;
}
setCustomErr(false);
email &&
email.indexOf("@") > -1 &&
onValidated({
EMAIL: email,
});
}
return (
<form id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" onSubmit={(e) => handleSubmit(e)} className="validate">
<div id="mc_embed_signup_scroll" className="form-inner">
<div className="mc-field-group">
<div className="form-group">
<input type="email" name="email" onChange={setEmail} className="form-control required email" id="mce-EMAIL" placeholder="Email"/>
</div>
{customErr && (
<div htmlFor="mce-EMAIL" className="mce_inline_error">This field is required.</div>
)}
</div>
<div className="form-group">
<button type="submit" name="subscribe" id="mc-embedded-subscribe" className="btn">Subscribe</button>
</div>
<div id="mce-responses" className="form-group-messages">
{status === "sending" && (
<div className="mc__alert mc__alert--sending">
sending...
</div>
)}
{status === "error" && (
<div className="response" id="mce-error-response">{message}</div>
)}
{status === "success" && (
<div className="response" id="mce-success-response">{message}</div>
)}
</div>
<div style={{position: "absolute", left: "-5000px"}} aria-hidden="true"></div>
</div>
</form>
);
};
由于某种原因,我收到了电子邮件。indexOf不是handlessubmit上的函数错误。猜猜问题出在哪里?请帮助
状态更新不同步的。这意味着当您执行setEmail(e.currentTarget.email.value)
email
的值不会立即更新:这样就可以批量调用多个state。
因为这个。道具和这个。状态可以异步更新不应该依赖它们的值来计算下一个状态。
Ref
更新如下:
const handleSubmit = (e) => {
e.preventDefault();
const temp = e.currentTarget.email.value;
// you may need a guard here like if (typeof temp === 'undefined') {...
setEmail(temp);
console.log(temp.length);
if(temp.length === 0) {
setCustomErr(true);
return;
}
setCustomErr(false);
if (temp.indexOf('@') > -1) {
onValidated({
EMAIL: temp,
});
}
}
您可能还需要一个警卫来检查e.currentTarget.email.value
的实际值,如果它可能缺失。比如:
if (typeof e.currentTarget.email.value === 'undefined')