我正在使用React钩子构建一个应用程序。
但问题是我可以故意点击两次按钮来发生错误。
所以我想在点击按钮时使用useState发送api请求时禁用该按钮。
然而,发送api和useState都是异步工作的,可能很难预料它是如何工作的。
因此,我想出了在React中使用setState回调函数的想法,但由于我是React钩子的新手,很难理解如何在React钩子中使用setState回调函数。
这是代码:
const submitForm = (values: IAgreeMentValues) => {
const userActivate = Object.assign(props.currentUserObject, values, {c})
delete userActivate.email
const userActivateJSON = JSON.stringify(userActivate)
if(values.is14YearsOldOrOlder && values.isAcceptedPrivacyPolicy && values.isAcceptedTerm) {
setButtonState(true)
activateUser(userActivateJSON).then(response => {
if(response.data.result.canLogin) {
popupStore.add({
type: 'alert',
title: t('signUp.agreeMent.registeredCompleted'),
actionString: t('popUpAlert.ok'),
onSubmit: isMobile ? pushToAppStore : pushToLogin
})
} else {
popupStore.add({
type: 'alert',
title: t('error.occured'),
actionString: t('popUpAlert.ok')
})
}
})
.catch(response => {
setButtonState(false)
popupStore.add({
type: 'alert',
title: response.response.data.error.message,
actionString: t('popUpAlert.ok'),
})
})
} else {
popupStore.add({
type: 'alert',
title: t('signUp.agreeMent.mustBeChecked'),
actionString: t('popUpAlert.ok')
})
}
};
return (
<>
<div className='signup-step-wrap'>
<div className='agree-check-box'>
<Formik enableReinitialize={true} initialValues={termsAllSelected}
onSubmit={ (values) => submitForm(values)}>
{({ values, handleChange, handleSubmit }) => (
<form onSubmit={handleSubmit}>
<ul className='check'>
<li>
<Field type='checkbox' name={`isAcceptedMarketingEmail`} id={`agree4`} onChange={handleChange} />
<label htmlFor={`agree4`}>{t('signUp.agreeMent.isAcceptedMarketingEmail')}</label>
</li>
<li>
<Field type='checkbox' name={`isAcceptedMarketingSms`} id={`agree5`} onChange={handleChange} />
<label htmlFor={`agree5`}>{t('signUp.agreeMent.isAcceptedMarketingSms')}</label>
</li>
</ul>
<div className='btn-btm-signin'>
<button className='btn-signin active' type='submit' disabled={currentButtonState} style={currentButtonState ? {background: '#e2e2e2'}:{background: '#1f1f1f'}}>{t('signUp.agreeMent.next')}</button>
</div>
</form>
)}
</Formik>
</div>
</div>
</>
)
您还应该在then
中使用setButtonState(false)
activateUser(userActivateJSON).then(response => {
if(response.data.result.canLogin) {
popupStore.add({
type: 'alert',
title: t('signUp.agreeMent.registeredCompleted'),
actionString: t('popUpAlert.ok'),
onSubmit: isMobile ? pushToAppStore : pushToLogin
})
} else {
popupStore.add({
type: 'alert',
title: t('error.occured'),
actionString: t('popUpAlert.ok')
})
}
setButtonState(false)
})