首页 > 解决方案 > 如何等到状态更新

问题描述

我正在使用 React,但我遇到了状态问题,因为它不会立即更新。我知道以前有人问过这个问题,但我在处理异步和等待时也遇到了麻烦。它似乎也不起作用(也许我没有把它放在正确的地方)。

我有一个表格,它在更新状态错误之前登录

这是代码

   import React, { useState } from "react";

function App() {
  const [errorName, setErrorName] = useState(false);
  const [errorPassword, setErrorPassword] = useState(false);

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

    if (!e.target[0].value) {
      setErrorName(true);
    }
    if (!e.target[1].value) {
      setErrorPassword(true);
    }
    if (!errorName && !errorPassword) {
      alert("You have logged in succesfully!");
    }
  };
  return (
    <div className="App">
      <header className="App-header">
        <form onSubmit={handleSubmit}>
          <input placeholder="enter your name" />
          <p style={errorName ? { display: "block" } : { display: "none" }}>
            You have not entered your name
          </p>
          <input placeholder="enter your password" />
          <p style={errorPassword ? { display: "block" } : { display: "none" }}>
            You have not entered your password
          </p>
          <button type="submit"> Submit</button>
        </form>
      </header>
    </div>
  );
}

export default App;

标签: reactjsasynchronoususe-state

解决方案


将值保存在局部变量中:

const handleSubmit = (e) => {
  e.preventDefault();
  const newErrorName = !e.target[0].value;
  const newErrorPassword = !e.target[1].value;
  if (newErrorName) {
    setErrorName(true);
  }
  if (newErrorPassword) {
    setErrorPassword(true);
  }
  if (!newErrorName && !newErrorPassword) {
    alert("You have logged in succesfully!");
  }
};

但您也应该考虑使用该required属性,让用户的浏览器处理它:

<input required placeholder="enter your name" />
<input required placeholder="enter your password" />

如果您必须等待状态更新,您可以使用useEffect. 从上面删除alert,并添加:

setFormJustChanged(true);

handleSubmit并添加:

const [formJustChanged, setFormJustChanged] = useState(false);
useEffect(() => {
  if (formJustChanged && (errorName || errorPassword)) {
    // There was an error
  } else {
    alert("You have logged in succesfully!");
  }
  // Don't enter this again until the form validates again
  setFormJustChanged(false);
}, [errorName, errorPassword, formJustChanged]);

推荐阅读