如果表单提交失败,我想恢复表单状态。这是关于在 reactjs 中防止多个表单提交的后续问题
const useCbOnce = (cb) => {
const [called, setCalled] = useState(false);
// Below can be wrapped in useCallback whenever re-renders becomes a problem
return (e) => {
if (!called) {
setCalled(true);
cb(e);
}
}
}
const MyForm = (props) => {
const [name, setName] = useState();
const handleSubmit = useCbOnce((e) => {
e.preventDefault()
if (name) {
//all is good
} else {
console.log('please enter the name and submit again')
// name is empty I need to restore the form state to allow the user to set and resubmit
}
console.log('submitted!')
});
return <form onSubmit={ handleSubmit }><input onChange={ (e) => setName(e.target.value) } /></form>;
}
假设我提交了一个表单而不设置名称!我想恢复以前的表单状态,以便 usr 可以填写名称并重新提交表单。基本上再次调用setCalled(false)但不确定在哪里做。