Formik-TypeError:无法读取未定义的属性'type'?

时间:2020-01-23 12:26:38

标签: javascript reactjs typeerror formik

我几乎只有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({

不确定我在这里做错了什么吗?

3 个答案:

答案 0 :(得分:2)

使用setFieldValue辅助函数代替field.onChange

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

答案 1 :(得分:1)

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

通过添加修复它

<Formik initialValues={{}} onSubmit={handleSubmit}>

这为我修好了!

答案 2 :(得分:0)

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