【问题标题】:How to wait until state is updated如何等到状态更新
【发布时间】:2020-11-19 00:43:11
【问题描述】:

我正在使用 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;

【问题讨论】:

    标签: reactjs asynchronous use-state


    【解决方案1】:

    将值保存在局部变量中:

    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]);
    

    【讨论】:

    • 请问有什么方法可以使它与 async、await 或任何其他方法一起工作?
    • 你需要什么样的异步逻辑?你能说明异步部分涉及的地方吗?
    • 我在寻求替代方案,因为由于某种原因,它在我正在工作的大型项目中仍然不起作用(这是减少)。我认为异步逻辑将适用,因为我应该等待状态更新,然后询问是否有任何错误。顺便感谢您的宝贵时间!
    • 如果先保存变量中的值,就不用等状态更新了吧?
    • 由于某种原因,在这个其他项目中,我仍然需要等待状态更新,即使我将值保存在变量中。
    猜你喜欢
    • 2020-05-10
    • 2020-12-28
    • 1970-01-01
    • 1970-01-01
    • 2020-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多