Реагировать Выберите mapPropsToValues - PullRequest
0 голосов
/ 09 января 2020

У меня проблема с mapPropsToValues ​​в моем родительском компоненте AddItem.

Я создал два дочерних компонента, которые используют React Select для правильного отображения информации из API в поле выбора, но я получаю сообщение об ошибке, когда моя mapPropsToValues ​​не комментируется:

Невозможно прочитать свойство 'value' из неопределенного

У меня возникла проблема с реквизитом, и я не уверен, как получить доступ к информации из getOptionKey или getOptionValue записано в дочерние компоненты.

мой основной компонент AddItem выглядит следующим образом:

function AddItem(props) {

    const {
    values,
    touched,
    errors,
    handleSubmit,
    handleChange,
    handleBlur,
    setFieldValue,
    setFieldTouched,
    isSubmitting
    } = props;
    

    return (
        <div className="addItem">
            <NextBackNavigation />
            <div style={imgContainer} className='imageContainer'>
                <div style={mainImg}>
                </div>
            </div>
            <div style={containerStyle} className='addItemContainer'>
                <Form onSubmit={handleSubmit} style={formStyle} type="l_id" name="l_id">
                    <LocationSelect
                        id="l_id"
                        type="l_id"
                        value={values.l_id}
                        onChange={handleChange}
                        onBlur={handleBlur}
                        error={errors.l_id}
                        touched={touched.l_id}
                    />
                    <CategorySelect
                        id="c_id"
                        type="c_id"
                        value={values.c_id}
                        onChange={handleChange}
                        onBlur={handleBlur}
                        error={errors.c_id}
                        touched={touched.c_id}
                    />
                    <label htmlFor="item_description" style={selectionLabel}>ITEM DESCRIPTION</label>
                    <input style={inputStyle}
                        id="item_description"
                        type="item_description"
                        onChange={handleChange}
                        onBlur={handleBlur}
                        value={values.item_description}
                        error={errors.item_description}
                        touched={touched.item_description}
                    />
                    {touched.item_description && errors.item_description && <div style={{ color: "red", marginTop: ".5rem", textAlign: "left"}}>{errors.item_description}</div>}
                    <label htmlFor="item_price" style={selectionLabel}>PRICE</label>
                    <input style={inputStyle}
                        id="item_price"
                        type="item_price"
                        onChange={handleChange}
                        onBlur={handleBlur}
                        value={values.item_price}
                        error={errors.item_price}
                        touched={touched.item_price}
                    />
                    {touched.item_price && errors.item_price && <div style={{ color: "red", margin: "0 .5rem", textAlign: "left"}}>{errors.item_price}</div>}
                    <button style={buttonStyle} className="submit" disabled={isSubmitting}>SUBMIT</button>
                </Form>
            </div>
        </div>
    );
};


const FormikAdditemForm = withFormik({

    mapPropsToValues: props => ({
        l_id: props.l_id.value || "",
        c_id: props.c_id.value || "",
        item_description: props.item_description.value || "",
        item_price: props.item_price.value || ""
      }),

    validationSchema: Yup.object().shape({
        l_id: Yup.string()
            .ensure()
            .required("*Market is a required field"),
        c_id: Yup.string()
            .ensure()
            .required("*Item is a required field"),
        item_description: Yup.string()
            .required("*Description is a required field"),
        item_price: Yup.string()
            .required("*Price is a required field")
    }),

    handleSubmit(values, { resetForm, setSubmitting }) {
        console.log(values);
        axios
            .post("https://build-week-africanl_idplace.herokuapp.com/api/users/:id/items", values)
            .then(res => {
                console.log(res);
                resetForm();
                setSubmitting(false);
            })
            .catch(err => {
                console.log(err); // There was an error creating the data and logs to console
                setSubmitting(false);
            });
    }
})(AddItem);


export default FormikAdditemForm;

компоненты почти идентичны, за исключением другого набора информации из API, поэтому ниже я приведу только один:

function LocationSelect(props)  {

    const [location, setLocation] = useState([]);

    useEffect(() => {
        axios
            .get("https://build-week-africanmarketplace.herokuapp.com/api/location")
            .then(res => {
                console.log(res)
                setLocation(res.data)
            })
            .catch(err => {
                console.log(err); // There was an error creating the data and logs to console
            });
    },[])

    return (
        <div style={{ margin: "1rem 0" }}>
            <label htmlFor="locations" style={selectionLabel}>MARKET LOCATION</label>
            <Select
                id="l_id"
                getOptionLabel={location =>
                    `${location.country}`
                  }
                getOptionValue={location => 
                    `${location.id}`
                }
                value={location.id}
                searchable={true}
                options={location}
            />
            {!!props.error && props.touched && (
                <div style={{ color: "red", marginTop: ".5rem", float: "left"}}>
                    {props.error}
                </div>
            )}
        </div>
    )
}

export default LocationSelect;

Я не уверен, почему значения возвращаются неопределенными, когда я разместил метку и значение в дочернем компоненте.

Любой совет приветствуется .

...