SetState无法在React Final Form中的onSubmit上工作

时间:2020-04-15 05:29:06

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

在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不更新状态。我不知道为什么谁能解释并告诉我该问题的解决方案是什么?

1 个答案:

答案 0 :(得分:2)

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

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