[英]how to disable a button in react after it is clicked and enable it back when a response is received from backend code
1). 1). There is a form with "Save" button 2).
有一个带有“保存”按钮的表格 2)。 When user clicks save - I want the button to be disabled till backend code sends a response that the form was saved successfully.
当用户点击保存时——我希望按钮被禁用,直到后端代码发送一个表单已成功保存的响应。 3).
3). The button should be enabled back after backend provides response
该按钮应在后端提供响应后重新启用
Why do i need this change:- when user clicks on save multiple times(say n) at once - the backend function for same data gets called for n times and data is saved n times.为什么我需要此更改:- 当用户一次单击多次保存(比如 n)时 - 相同数据的后端 function 被调用 n 次并且数据被保存 n 次。 Hence what to handle this - please suggest
因此如何处理这个 - 请提出建议
Code:代码:
<CustomButton
save={(e) => console.log('Submitting form...')}
class='ml-2'
/>
CustomButton code:自定义按钮代码:
const CustomButton = (props) => {
let className = "button btn btn-sm";
if (props.class) className += ` ${props.class}`;
else className += " mr-2";
return (
<>
{props.save ?
<Button
className={className}
id="button_success"
type="submit"
onClick={e => props.save(e)}
disabled={props.disable ? props.disable : false}
>
Save
</Button>
:
not familiar with react不熟悉反应
A good pattern for this is to handle the disabled/enable outside of the button.一个好的模式是在按钮外部处理禁用/启用。
const usage = () => {
const [isLoading, setIsLoading] = useState(false);
const doRequest = () => {
setIsLoading(true);
doTheThing().then(() => {
// handle request here
}).finally(() => {
setIsLoading(false);
});
}
return (<CustomButton
save={() => doRequest()}
disable={isLoading}
class='ml-2'
/>);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.