Formik - TypeError: Cannot read property 'type' of undefined?

Formik - TypeError: Cannot read property 'type' of undefined?

我差不多 copy pasted this code from here :

function Checkbox(props) {
  return (
    <Field name={props.name}>
      {({ field, form }) => (
        <label>
          <input
            {...field}
            type="checkbox"
            checked={field.value.includes(props.value)}
            onChange={() => {
              const set = new Set(field.value);
              if (set.has(props.value)) {
                set.delete(props.value);
              } else {
                set.add(props.value);
              }
              field.onChange(field.name)(Array.from(set)); //the problem seems to lie here somewhere!
              form.setFieldTouched(field.name, true);
            }}
          />
          {props.value}
        </label>
      )}
    </Field>
  );
}

function App() {
  return (
    <Formik
      initialValues={{ roles: [] }}
      onSubmit={values => alert(JSON.stringify(values, null, 2))}
    >
      {formik => (
        <div>
          Clicking checks affects `VALUES` and `ERRORS` but never `TOUCHED`...
          <div>
            <Checkbox name="roles" value="admin" />
            <Checkbox name="roles" value="customer" />
          </div>
          <br />
          VALUES:
          <pre>{JSON.stringify(formik.values, null, 2)}</pre>
          ERRORS:
          <pre>{JSON.stringify(formik.errors, null, 2)}</pre>
          TOUCHED:
          <pre>{JSON.stringify(formik.touched, null, 2)}</pre>
        </div>
      )}
    </Formik>
  );
}

沙盒似乎在工作,但每当我在本地选中一个复选框时,我得到 TypeError: Cannot read property 'type' of undefined

TypeError: Cannot read property 'type' of undefined
(anonymous function)
node_modules/formik/dist/formik.esm.js:659
  656 |   dispatch({
  657 |     type: 'SET_ERRORS',
  658 |     payload: errors
> 659 |   });
  660 | }, []);
  661 | var setValues = useEventCallback(function (values) {
  662 |   dispatch({

不确定我做错了什么?

而不是 field.onChange 使用 setFieldValue 辅助函数

field.onChange(field.name)(Array.from(set)); //the problem seems to lie here somewhere!

替换为:

form.setFieldValue(field.name,(Array.from(set)));

https://codesandbox.io/embed/formik-checkbox-example-l9p1p?fontsize=14&hidenavigation=1&theme=dark

你的 react-redux 中有一些动作问题所以我建议你检查你的动作类型我认为你的动作类型没有定义这就是为什么它显示未定义并出现错误。

如果有人在产生上述错误的基础上偶然发现了这个问题,那可能是因为您错过了将 initialValues 添加到 Formik 组件。

只需添加

即可修复
<Formik initialValues={{}} onSubmit={handleSubmit}>

这帮我修好了!