微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在 React 中提交表单时禁用提交按钮在使用 useState 钩子时无法按预期工作

如何解决在 React 中提交表单时禁用提交按钮在使用 useState 钩子时无法按预期工作

    const [buttondisabled,setButtondisabled] = useState(false);

    const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
        event.preventDefault();
        setButtondisabled(true);

        const response = await fetch(
            "http://localhost:5000/....",{
                method: "POST",body: JSON.stringify(state),},);
        setButtondisabled(false);

        const responseJson = await response.text();

    };

// Button 
<button disabled={buttondisabled} type="submit">Submit form</button>

我希望按钮在获取过程中被禁用(有一个指示器),但它不起作用。我究竟做错了什么?这也是处理禁用按钮的合适方法吗?或者有更好的方法

解决方法

这是工作代码。看起来你的 API 是超快的,你看不出区别。 https://codesandbox.io/s/competent-hellman-tf346?file=/src/App.tsx:0-817

import * as React from "react";
import "./styles.css";

export default function App() {
  const [buttonDisabled,setButtonDisabled] = React.useState(false);

  const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
    console.log("here");
    event.preventDefault();
    setButtonDisabled(true);

    const response = await fetch("http://localhost:5000/....",{
      method: "POST",body: JSON.stringify({})
    });
    const responseJson = await response.text();
    setButtonDisabled(false);
  };
  return (
    <div className="App">
      <form onSubmit={handleSubmit}>
        <button disabled={buttonDisabled} type="submit">
          Submit form
        </button>
      </form>
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。