我僅在 api 請求成功時才嘗試禁用按鈕,否則如果不成功,則仍應啟用該按鈕。我有以下狀態欄位。
this.state = {
requestDisabled: false,
};
在我的處理程式中:
sendSmsCode = async () => {
const { actions } = this.props;
sendSms(phone)
.then((data) => {
this.setState({
requestDisabled: true
}, () => {
actions.showSmsNotification(data);
});
})
.catch(err => actions.showSmsNotification(err));
setTimeout(() => {
this.setState({
requestDisabled: false
});
}, 10000);
};
這是我的按鈕:
<Button type="button" disabled={this.state.requestSmsDisabled} onClick={this.sendSmsCode} variant="outlined" color="primary">
<Typography classes={{ root: classes.requestSmsButtonText }}>
Send SMS
</Typography>
</Button>
但是,出于某種原因,在這兩種情況下,該按鈕都被禁用了 10 秒鐘。來自 api 的通過和失敗回應。這里有什么東西嗎?
uj5u.com熱心網友回復:
您的 sendSms() 函式回傳一個 axiosResponse物件。因此,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
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/367192.html
標籤:javascript 反应 反应原生 异步 设置状态
下一篇:無法滾動ReactNative
