简体   繁体   中英

React Native TypeError: undefined is not an object ('evaluating useFormikContext.errors')

I am developing an app with react native. using formik for forms, I am getting this error 'TypeError: undefined is not an object (evaluating '_useFormikContext.errors') 这是我得到的错误 '

import { useFormikContext } from "formik";

import { ErrorMessage } from "./index";
import ImageInputList from "../ImageInputList";

function FormImagePicker({ name }) {
  const { errors, setFieldValue, touched, values } = useFormikContext();
  const imageUris = values[name];

  const handleAdd = (uri) => {
    setFieldValue(name, [...imageUris, uri]);
  };
  const handleRemove = (uri) => {
    setFieldValue(
      name,
      imageUris.filter((imageUri) => imageUri !== uri)
    );
  };

  return (
    <>
      <ImageInputList
        imageUris={imageUris}
        onAddImage={handleAdd}
        onRemoveImage={handleRemove}
      />
      <ErrorMessage error={errors[name]} visible={touched[name]} />
    </>
  );
}

export default FormImagePicker;

You are trying to get an object property when is not defined yet, try doing this:

{errors && (<ErrorMessage error={errors[name]} visible={touched[name]} />)}

If this is not what you want, try to find a different solution but always remember that you can't get errors[name] just like that, you have to be sure that errors exists before doing that.

Hope this solves your problem, Cheers!

You should call FormImagePicker inside a formik component:

 <AppForm
    initialValues={{
      title: "",
      price: "",
      description: "",
      category: null,
      images: [],
    }}
    validationSchema={validationSchema}
    onSubmit={(values) => console.log(values)}
  >
    <FormImagePicker name="images" />      // ==> here <==

    <AppFormField maxLength={255} name="title" placeholder="Title" />
    
    <AppFormField
      keyboardType="numeric"
      maxLength={8}
      name="price"
      placeholder="Pirce"
      width={120}
    />
    <AppFormPicker
      item={categories}
      name="category"
      placeholder="Category"
      width={"50%"}
      PickerItemComponent={CategoryPickerItem}
      numberOfColumns={3}
    />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM