如何防止useEffect在加载页面时显示验证错误



const Login=((=>{

const[errors,setErrors]=useState({}(

var newErrors={}

const formValidation=((=>{如果(name=="({newErrors.name=name不能是Blank}

if (email === "") {
newErrors.email = <h1 className="text-red-800 text-center"> Email Address Is Required</h1>
} else if (/^w+([.-]?w+)*@w+([.-]?w+)*(.w{2,3})+$/.test(email)) {
newErrors.email = <h1 className="text-red-800 text-center">Email address is invalid</h1>
} else {
newErrors.email = <h1 className="text-green-800 text-center ">Email is Valid</h1>
}
if (password === "") {
newErrors.password = <h1 className="text-red-800 text-center">Password Is Required</h1>
} else if (!/^(?=.*d)(?=.*[a-z])(?=.*[A-Z]).{8,15}$/.test(password)) {
newErrors.password = <h1 className="text-red-800 text-center">Invalid Password Format</h1>
} else {
newErrors.password = <h1 className="text-green-800 text-center ">Correct Password</h1>
}
setErrors(newErrors)

}

const handleSubmit=(e(=>{e.preventDefault((

formValidation()
console.log({ name, email, password })

}

useEffect(((=>{if(newErrors({表单验证((enter code here}},[姓名,电子邮件,密码](

return (
<div
className="login grid place-content-center  
bg-gradient-to-r from-purple-900 via-purple-1000 to-blue-800 "
>
<form
className="card grid place-content-center  h-96 w-96  
"
onSubmit={handleSubmit}
>
<label htmlFor="">name:</label>
<input
type="text"
value={name}
placeholder="Enter Your Name"
onChange={(e) => setName(e.target.value)}
/>
{errors.name}
</form>
</div>

)}

导出默认登录

我的方法是添加一个名为loadingconst {loading,setLoading}= useState(false)的状态当然,在加载时将加载设置为true。并使用{ loading? null : errors.name}有条件地呈现错误

相关内容

  • 没有找到相关文章