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


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

最新更新