【问题标题】:SetState not working on onSubmit in React Final FormSetState 在 React Final Form 中无法处理 onSubmit
【发布时间】:2023-03-22 04:31:01
【问题描述】:

我在 onSubmit 函数上使用 setContactInfo/setPassword 更新状态时遇到问题。谁能帮帮我?

这是反应的最终形式

<Form
  onSubmit={onSubmit}
  validate={validation}
  render={({ handleSubmit, form, submitting, pristine, values }) => (
    <form onSubmit={handleSubmit}>
      <FormGroup>
        <Field name='contactInfo'>
          {({ input, meta }) => (
            <div className='erow'>
              <Input
                {...input}
                type='text'
                id='contactInfoID'
                placeholder='Email / Phone number'
              />
              {errorShowing(meta)}
            </div>
          )}
        </Field>
        <Field name='password'>
          {({ input, meta }) => (
            <div className='erow'>
              <Input
                {...input}
                type='password'
                id='passwordID'
                placeholder='Password'
              />
              {errorShowing(meta)}
            </div>
          )}
        </Field>
      </FormGroup>
      <FormGroup>
        <div className='submit-btn text-center'>
          <Button
            type='submit'
            id='submitID'
            className='btn btn-dark px-5 py-2'
            disabled={submitting}
          >
            Signup
          </Button>
        </div>
      </FormGroup>
    </form>
  )}
></Form>

这些是功能。

  ...................
  ...................

  const [contactInfo, setContactInfo] = useState('');
  const [password, setPassword] = useState('');

  const onSubmit = (values) => {
    console.log(values);
    setContactInfo(values.contactInfo);
    setPassword(values.password);
    console.log(contactInfo, password);
    window.alert(JSON.stringify({ contactInfo, password }, 0, 2));
  };

  ..............
  ..............

这里的 setContactInfo 和 setPassword 没有更新状态。我不知道为什么。谁能解释并告诉我这个问题的解决方案是什么?

【问题讨论】:

    标签: reactjs react-hooks state react-final-form


    【解决方案1】:

    因为 setContactInfo 和 setPassword 是异步的,所以在调用此方法后您无法读取更新的值。试试

    useEffect(()=>{
        console.log(contactInfo, password);
    },[contactInfo, password]);
    

    【讨论】:

      猜你喜欢
      • 2016-04-13
      • 2020-07-12
      • 2018-11-16
      • 1970-01-01
      • 2019-06-13
      • 1970-01-01
      • 2021-01-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多