React表单验证状态未更新:错误信息无法显示问题求助
React表单验证错误信息无法显示的解决办法
你的问题出在两个关键环节,直接修正就能解决:
渲染错误信息时用错了变量
页面错误提示区域写的是{seterr.Email},但seterr是用来更新state的函数,不是存储错误信息的state本身。必须改成{err.Email},才能正确读取错误文本。修改错误信息后未更新state
在login函数里,你创建了NewErr并赋值了错误内容,但没有调用seterr(NewErr)更新state。React组件只有在state变化时才会重新渲染页面,所以就算控制台能看到错误信息,页面也不会同步显示。
修正后的完整代码如下:
import { useState } from 'react'; function LoginForm() { const [logindata, setLogindata] = useState({ customeremail: '', customerpass: '' }) const [err, seterr] = useState({ Email: '', Passwordnew: '' }); const handlechange = event => { const val = event.target.value const name = event.target.name setLogindata({ ...logindata, [name]: val }) } function login() { const NewErr = {...err}; // 重置之前的错误信息,避免残留 NewErr.Email = ''; NewErr.Passwordnew = ''; if (logindata.customeremail === "") { NewErr.Email = "Email should not be empty"; } if (logindata.customerpass === "") { NewErr.Passwordnew = "Password should not be empty"; } // 调用seterr更新state,触发组件重渲染 seterr(NewErr); } return ( <> <div className="container"> <div className="row"> <div className="col-12 col-sm-12 col-md-6 col-lg-6 main-col offset-md-3"> <div className="mb-4"> <form method="post" action="home" id="CustomerLoginForm" acceptCharset="UTF-8" className="contact-form"> <div className="row"> <div className="col-12 col-sm-12 col-md-12 col-lg-12"> <div className="form-group"> <label htmlFor="CustomerEmail">Email</label> <input type="email" name="customeremail" placeholder="" id="CustomerEmail" className="" autoCorrect="off" autoCapitalize="off" autoFocus="" onChange={handlechange} value={logindata.customeremail} required={true} /> </div> {/* 有错误信息时才显示提示框,避免空框占位 */} {err.Email && ( <div className="alert alert-danger" role="alert"> {err.Email} </div> )} </div> <div className="col-12 col-sm-12 col-md-12 col-lg-12"> <div className="form-group"> <label htmlFor="CustomerPassword">Password</label> <input type="password" name="customerpass" placeholder="" id="CustomerPassword" className="" onChange={handlechange} value={logindata.customerpass} /> </div> {err.Passwordnew && ( <div className="alert alert-danger" role="alert"> {err.Passwordnew} </div> )} </div> </div> <div className="row"> <div className="text-center col-12 col-sm-12 col-md-12 col-lg-12"> <input type="button" style={{ backgroundColor: '#000', color: '#fff' }} className="btn mb-3" value="Sign In" onClick={login} /> <p className="mb-4"> <a href="#" id="RecoverPassword">Forgot your password?</a> | <a href="register.html" id="customer_register_link">Create account</a> </p> </div> </div> </form> </div> </div> </div> </div> </> ) } export default LoginForm;
额外优化说明:
- 每次验证前重置错误信息,避免上次的错误残留
- 用条件渲染控制提示框显示,不会出现空的红色提示区域
内容的提问来源于stack exchange,提问作者Rushi Bhatt
相关产品推荐
相关产品推荐

