如何在不触发警告的情况下更新Formik渲染中的状态

时间:2020-09-04 10:24:51

标签: reactjs formik

我需要在父组件中使用Formik错误,我编写了这段代码,但这似乎是一种反模式。

它会触发警告Cannot update a component ("MyParent") while rendering a different component ("Formik"). To locate the bad setState() call inside "Formik"

有更好的方法吗?

const MyForm = ({ setErrors }) => {
  return (
    <Formik>
      {({
        values,
        errors,
        touched,
        handleChange,
        handleBlur,
        handleSubmit,
        isSubmitting,
        isValid,
        submitForm,
      }) => {
        setErrors(errors)
        return (
          <Form>
            ...
          </Form>
        )
      }}
      </Formik>
  )
}

const MyParent = () => {
  const [formErrors, setFormErrors] = useState({})

  return (
    <MyForm setErrors={setFormErrors} />
  )
}

0 个答案:

没有答案