【问题标题】:How to use callback function in React hooks when value is submitted?提交值时如何在 React 挂钩中使用回调函数?
【发布时间】:2020-06-24 06:15:21
【问题描述】:

我正在使用 React hooks 构建一个应用程序。

但问题是我可以故意单击按钮两次以发生错误。

所以我想在单击按钮时使用 useState 发送 api 请求时禁用该按钮。

但是,发送 api 和 useState 都是异步工作的,很难预料它是如何工作的。

因此我想出了在 React 中使用 setState 回调函数的想法,但是由于我是 React hooks 的新手,所以很难掌握如何在 React hooks 中使用 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>
      </>
    )

【问题讨论】:

  • 我没有看到你在哪里设置了const [currentButtonState, setButtonState] = React.useState(false);。这是一个例子codesandbox.io/s/objective-flower-c1bh7
  • 谢谢。就像示例一样,我将 setButtonState 放在 submitForm 函数的顶部。

标签: reactjs react-hooks


【解决方案1】:

您还应该在thensetButtonState(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)
        })

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-05
    • 2022-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-23
    • 1970-01-01
    • 2010-11-09
    相关资源
    最近更新 更多