reactjs - handleSubmit() 上的值在控制台日志中显示未定义
问题描述
相同的代码在以前的机器上运行良好。
现在由于某种原因,控制台中的值(在 handleSubmit() 中)显示未定义的电子邮件、全名和密码,然后它到达 catch 块,说出现了问题!帮助。我有一个注册表单:
export default function MerchantCreateAccountForm() {
其中定义了电子邮件、密码和姓名等常量:
// set error messages to display to the user
const [nameError, setNameError] = useState(null);
const [emailError, setEmailError] = useState(null);
const [passwordError, setPasswordError] = useState(null);
// set initial state value(s)
const [fullName, setFullName] = useState('');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [errors, setErrors] = useState({});
const authContext = useContext(AuthContext);
主要是,在handleSubmit() 中需要为电子邮件、fullName 和密码的未定义值提供帮助。 后来它到达了捕获块(出了点问题),但这可能是另一个问题。
这是功能:
const handleSubmit = (e) => {
try {
e.preventDefault();
console.log("email is: " +email); //showing undefined in console. HELP
console.log("name is: "+fullName); //showing undefined in console. HELP
console.log("password is: "+password); //showing undefined in console. HELP
const merchantSignupData =
{
data:
{
name: fullName,
email: email,
password: password,
client_id: 'testclient',
client_secret: 'testpass'
},
type: 'POST',
url: 'merchant-signup',
success: authContext.merchantSignupSuccess,
error: authContext.networkError
};
merchantSignupObject.fullName, merchantSignupObject.password);
authContext.merchantSignup(merchantSignupData);
}
catch{
console.log("something went wrong!");
//need to add error handling here
}
}
虽然我在这里使用了验证,但效果很好,以防万一这可能会妨碍设置数据:
// for every change in our state this will be fired
// we add validation here and disable the save button if required
useEffect(() => {
// we want to skip validation on first render
if (firstRender.current) {
firstRender.current = false
return
}
// here we can disable/enable the save button by wrapping the setState function
// in a call to the validation function which returns true/false
//setDisabled(formValidation())
formValidation();
}, [fullName, password]) // any state variable(s) included in here will trigger the effect to run
// here we run any validation, returning true/false
const formValidation = () => {
let newErrors = {}
var error = false;
if (fullName === "") {
newErrors.fullName = 'Name cant be blank!'
}
if (email === "") {
newErrors.email = 'Email cant be blank!'
}
if (!(/.+@.+\.[A-Za-z]+$/.test(email))) {
newErrors.email = 'Enter a valid email id';
}
if (!(/(?=.{7,255}$)(?=.*[A-Z])(?=.*[a-z])(?=.*\d)/.test(password))) {
newErrors.password = 'Invalid Password Format';
}
setNameError(errors.name)
setEmailError(errors.email)
setPasswordError(errors.password)
if (errors != null) {
//alert("reached")
setErrors(newErrors);
// $("#signup-submit").addremoveAttr("disabled")
}
else {
alert("reached here")
setNameError(errors.fullName)
setEmailError(errors.email)
setPasswordError(errors.password)
// $("#signup-submit").removeAttr("disabled")
}
}
const showError = () => {
alert('error!');
}
这是我的主要形式:
return (
<form onSubmit={handleSubmit()}>
<div className="row">
<div className="col-md-4 col-sm-6 col-xs-12">
<div className="signup">
<h3>{lang.merchant_signup_create_account}</h3>
<p>{lang.merchant_signup_account_already}<a href="/linktologinpagecomponentlatertodo">{lang.merchant_signup_sign_in}</a></p>
<div className="form-group has-error">
<input type="text" required="required" name="fullName"
value={fullName}
placeholder={lang.merchant_signup_name_placeholder}
onChange={e => setFullName(e.target.value)} />
<label htmlFor="input" className="control-label">{lang.merchant_signup_name}</label>
<i className="bar"></i>
<div className="error">
<div className="error-msg" role="alert">
{errors.fullName && <p>{errors.fullName}</p>}
</div>
</div>
</div>
<div className="form-group">
<input type="text" required="required"
placeholder={lang.merchant_signup_email_placeholder} onChange={e => setEmail(e.target.value)} />
<label htmlFor="E-mail" className="control-label">{lang.merchant_signup_email}</label><i className="bar"></i>
<div className="error">
<div className="error-msg" role="alert">
{errors.email && <p>{errors.email}</p>}
</div>
</div>
</div>
<div className="form-group">
<input type="password" required="required" placeholder={lang.merchant_signup_password_placeholder} onChange={e => setPassword(e.target.value)} />
<label htmlFor="Password" className="control-label">{lang.merchant_signup_password}</label><i className="bar"></i>
<div className="error">
<div className="error-msg" role="alert">
{errors.password && <p>{errors.password}</p>}
</div>
</div>
<ul className="p-suggest">
<li> {lang.merchant_signup_password_validation1}</li>
<li>{lang.merchant_signup_password_validation2}</li>
</ul>
<ul className="p-suggest">
<li>{lang.merchant_signup_password_validation3}</li>
<li>{lang.merchant_signup_password_validation4}</li>
</ul>
</div>
<p>{lang.merchant_signup_create_terms_warning}<a target="_blank" href="#">{lang.merchant_terms_condition}</a>.</p>
</div>
<ul className="list-inline">
{/* onClick={() => handleSubmit()} */},
<li><button type="submit" id="signup-submit" className="btn btn-danger create-account next-step">{lang.merchant_signup_create_account_btn}</button></li>
</ul>
</div>
<div className="col-md-8 col-sm-6 col-xs-12">
<img className="img-responsive" src={storeImg} />
</div>
</div>
</form>
)
}
解决方案
正如你在这里看到的,
确保在将函数传递给组件时没有调用该函数:
因此,将您的表单onSubmit
方法调用更改为
<form onSubmit={handleSubmit}>
或者
<form onSubmit={() => handleSubmit()}>
推荐阅读
- c# - 搜索可用管道时出现意外行为
- node.js - 无法从文件中读取凭据
- swift - 如何从我的过滤列表中删除单元格?
- ssas - 多维数据集问题上的 MDX 成员
- javascript - 即使应用程序在后台,如何保持后台计时器在本机反应中运行
- java - Spring Listener Container - 事务管理器 - Spring Retry - 在几个事务中
- python-3.x - 我是 ML 新手,我不明白 sklearn 部分
- linux - 如何设置默认的 xrander 模式
- java - 需要去掉聚合操作里面的三元算子
- json - jq:如何从相同类型的列表中检索元素?