如何仅在请求成功时禁用按钮 - 否则在反应中保持按钮启用
How to disable button only if the request is successful - otherwise keep button enabled in react
我试图仅在 api 请求成功时禁用按钮,否则如果不成功,按钮仍应启用。我有以下状态字段。
this.state = {
buttonDisabled: false,
};
这是我的按钮:
<Button type="button" disabled={this.state.buttonDisabled} onClick={this.send} variant="outlined" color="primary">
Send
</Button>
但是,由于某种原因,在这两种情况下按钮都被禁用了 10 秒。来自 api 的通过和失败响应。这里有什么事吗?
您的 sendSms() 函数 returns 一个 axios Response
对象。因此,data
对象将始终被填充并且永远不会抛出错误。
sendSmsCode = async () => {
const { actions } = this.props;
sendSms(phone)
.then((data) => {
// the data object is always populated with the response object and never throws an error
// therefore, this function will always set the state to disabled
this.setState({
requestSmsDisabled: true
}, () => {
actions.showSmsNotification(data);
});
})
// this is never invoked
.catch(err => actions.showSmsNotification(err));
setTimeout(() => {
this.setState({
requestSmsDisabled: false
});
}, 10000);
};
您需要检查 axios 调用的响应中的错误,无论是在 sendSms() 函数还是 sendSmsCode() 函数中,例如:
async function sendSms(phone) {
const options = {
method: 'POST',
headers: {
'content-type': 'application/json'
},
data: {
phone
},
url: `${API_ROOT}/sms`
};
// there are a number of ways to do this, it all depends on how you want to do it
const response = await axios(options);
if (response.status === 200) {
return response.data;
} else {
// do something to indicate an error, e.g. throw an error to get caught in your .catch() statement or return an error message
}
}
我试图仅在 api 请求成功时禁用按钮,否则如果不成功,按钮仍应启用。我有以下状态字段。
this.state = {
buttonDisabled: false,
};
这是我的按钮:
<Button type="button" disabled={this.state.buttonDisabled} onClick={this.send} variant="outlined" color="primary">
Send
</Button>
但是,由于某种原因,在这两种情况下按钮都被禁用了 10 秒。来自 api 的通过和失败响应。这里有什么事吗?
您的 sendSms() 函数 returns 一个 axios Response
对象。因此,data
对象将始终被填充并且永远不会抛出错误。
sendSmsCode = async () => {
const { actions } = this.props;
sendSms(phone)
.then((data) => {
// the data object is always populated with the response object and never throws an error
// therefore, this function will always set the state to disabled
this.setState({
requestSmsDisabled: true
}, () => {
actions.showSmsNotification(data);
});
})
// this is never invoked
.catch(err => actions.showSmsNotification(err));
setTimeout(() => {
this.setState({
requestSmsDisabled: false
});
}, 10000);
};
您需要检查 axios 调用的响应中的错误,无论是在 sendSms() 函数还是 sendSmsCode() 函数中,例如:
async function sendSms(phone) {
const options = {
method: 'POST',
headers: {
'content-type': 'application/json'
},
data: {
phone
},
url: `${API_ROOT}/sms`
};
// there are a number of ways to do this, it all depends on how you want to do it
const response = await axios(options);
if (response.status === 200) {
return response.data;
} else {
// do something to indicate an error, e.g. throw an error to get caught in your .catch() statement or return an error message
}
}