React js - useState returns onChange Form 函数内部和外部的不同值

React js - useState returns different values inside and outside of a onChange Form function

我想知道为什么 loginPassword.lengthloginPasswordError 内外不同 loginFormPasswordHandler

import React, {useState} from 'react';
import './styles.css'

const App = () => {

  const [loginPassword, setLoginPassword] = useState('');
  const [loginPasswordError, setLoginPasswordError] = useState();
  const [submitController, setSubmitController] = useState(false);

  const loginFormSubmitHandler = (e) => {
    e.preventDefault();
  }



  const loginFormPasswordHandler = (e) => {
    setLoginPassword(e.target.value);
    setLoginPasswordError(loginPassword.length < 8);
    console.log('login password length is(inside):'+loginPassword.length+' and the state is '+loginPasswordError)
    loginPassword.length > 8 ? setSubmitController(true) : setSubmitController(false);
  }

  console.log('login password length is(outside):'+loginPassword.length+' and the state is '+loginPasswordError)

  return(
  <React.Fragment>
    <div className="form-wrapper">
      <form onSubmit={loginFormSubmitHandler}>
        <input className={`${loginPasswordError && 'error'}`} type="password" id="password" name="password" placeholder="Password" onChange={loginFormPasswordHandler} />
        <div className={`submit-btn ${submitController ? '' : 'disable'}`}>
          <input type="submit" />
        </div>
      </form>
    </div>
  </React.Fragment>
  );
}

export default App;

我知道 useState 在状态改变时重新运行整个代码。但我无法理解这种行为。我不确定这是 Javascript 属性 还是 React 属性.

setState 是异步的,这意味着您的登录密码和错误状态值可能不会在您 运行 setLoginPassword 和 setLoginPasswordError 后立即更新。

下面的另一行在每次渲染时重新运行s,所以它会输出最新的值。

console.log('login password length is(outside):'+loginPassword.length+' and the state is '+loginPasswordError)