reactjs - useState 值在 reactjs 中落后了一步
问题描述
我正在处理登录/注册页面,我使用 useState 挂钩来检查密码是否强大。并显示用户他应该怎么做才能使他的密码更强大。但我注意到,当用户在密码字段中输入时,他们更新 useState 中的密码会延迟(在函数 handlePassword 的 console.log() 中)。因此我的函数 handlePassword 无法正常工作。
const [err,setError]=useState("")
const [password,setPassword]=useState("")
function handlePassword(event){
setPassword(event.target.value);
if(password.length<6){
console.log(password)
setError("password should contain 6 character")
}else if(!isInclude(password)){
setError("password should contain a special character")
}else{
setError("")
}
}
<input type="password" placeholder="password" required className="form-input" value={password} onChange={handlePassword} name="password" onClick={clearInput}/>
解决方案
没有延迟,setState 异步工作,将你的 console.log 放在函数之外,你会看到正确的结果。因此,出于同样的原因,您无法在设置状态后立即检查密码长度。相反,您需要这样做useEffect
;
useEffect(()=>{
if(password.length<6){
console.log(password)
setError("password should contain 6 character")
}else if(!isInclude(password)){
setError("password should contain a special character")
}else{
setError("")
}
}, [password])
推荐阅读
- google-cloud-platform - 谷歌云功能可以监听多个事件触发器吗?
- c++ - 将 RFC5114 中定义的 1024bit P 和 G 值加载到 boost uint1024
- mongodb - MongoDB保留满足条件的路径
- laravel - 'Unexpected token <' 包装 .vue 文件时
new to vue here and I am creating an area in the code for all my vue components to be rendered through a
blade.php
file (sfc). I installed the cli usingvue create projectN
- mongodb - MongoDB Atlas Golang mgo package "No reachable servers" error
- python - 如何将一个类对象的 id 传递给 django views.py 中的另一个类对象
- json - 在 get_json_object 的搜索字符串中包括 $
- javascript - How to pass a date parameter into a Coinbase Fetch API call?
- javascript - how to make a chart with foreach time
- python-2.7 - 如何将子列表中的两个值连接为python中的元组对坐标