首页 > 解决方案 > 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}/>  

标签: reactjsreact-hooksuse-state

解决方案


没有延迟,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])

推荐阅读