【问题标题】:Using SetTimeout() in React在 React 中使用 SetTimeout()
【发布时间】:2022-06-10 20:39:04
【问题描述】:

我正在尝试在一段时间后更改状态,以便我可以更改 DOM 并为此使用 setTimeout() 但我无法使其工作。这是代码:

  function Contact() {
  const [send, setSend] = useState(false);

  const submitHandler = async values => {
    const { fullname, email, subject, message } = values;

    if (fullname && email && subject && message) {
      const response = await fetch('/api/sendgrid', {
        method: 'post',
        body: JSON.stringify({
          fullname,
          email,
          subject,
          message,
        }),
      });
      console.log(response);
      if (response.status === 'ok') {
        setSend(true);
        setTimeout(() => {
          setSend(false);
        }, 3000);
      }
    }
    reset();
  };

  return <something/>

所以send 变量应该在 3 秒后改变,之后我需要 clearTimeout()。我应该在哪里进行更改?

【问题讨论】:

    标签: reactjs settimeout


    【解决方案1】:

    我真傻。我的最后一个 if 语句是错误的。应该是这样的。

    if (response.ok) {
        setSend(true);
        setTimeout(() => {
          setSend(false);
        }, 3000);
      }
    

    【讨论】:

    • 这与您在问题中提出的内容有何不同?
    • 是的,我什至没有检查我粘贴的内容。抱歉,我现在编辑了它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-07-06
    • 1970-01-01
    • 2016-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多