1

我想知道为什么loginPassword.length以及loginPasswordError内外不同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 属性。

4

1 回答 1

1

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

下面的另一行在每次渲染时都会重新运行,因此它将输出最新的值。

console.log('login password length is(outside):'+loginPassword.length+' and the state is '+loginPasswordError)
于 2021-06-24T05:10:37.047 回答