Formik и FieldArray Mapping с Typescript - PullRequest
       3

Formik и FieldArray Mapping с Typescript

0 голосов
/ 03 февраля 2020

Я новичок в React и Formik и все еще пытаюсь научиться им пользоваться. Я пытаюсь сопоставить элементы из массива элементов. Однако я не уверен, каков правильный синтаксис для отображения. Я получаю следующую ошибку:

"Ошибка типа: невозможно прочитать свойство 'map' of undefined"

Это начальные значения:

{
    "costs": [{
        "cost_Id": 1,
        "investment_Plan_Id": 1,
        "item": "abc",
        "amount": "3",
        "unit_Cost": "444"
    }, {
        "cost_Id": 2,
        "investment_Plan_Id": 1,
        "item": "xyz",
        "amount": "4",
        "unit_Cost": "99"
    }, {
        "cost_Id": 3,
        "investment_Plan_Id": 1,
        "item": "fff",
        "amount": "33",
        "unit_Cost": "5435"
    }]
}

Ниже приведен код с элементами не отображается правильно:


import React, { useState, useEffect } from 'react';
import { Formik, Field, FieldArray } from "formik";
import axios from 'axios';

const App: React.FC = () => {

    const [initialValues, setInitialValues] = useState();

    async function getInitialValues() {
        try {

             return await axios({
                method: "GET",
                url: "http://localhost:53132/api/Projects/1",
            })
                .then((response: any) => {

                //console.log(response);

                const initialValues = {
                    Costs: response.data.costs
                }

                console.log(initialValues);

                return initialValues;

            })
            .catch((error: any) => {
                console.log(error);
            });

        } catch (error) {
            console.error(error);
        }
    }

    useEffect(() => {
        getInitialValues().then(res => setInitialValues(res));

        return () => {
            //console.log(initialValues);
        };

    }, []);

    const handleOnSubmit = (values: any, actions: { setSubmitting: (arg0: boolean) => void; resetForm: () => void; }) => {
        console.log(values)
    };

    return initialValues ? (

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

                    {props => (

                        <form onSubmit={props.handleSubmit}>

                            <FieldArray

                                {...props.values.costs.map((method: { name: any}, index: any) => (

                                    <div key={index}>
                                        <input
                                            name={`costs.${index}.item`}
                                            value={method.name}
                                            onChange={props.handleChange}
                                        />

                                    </div>

                                ))}

                            />

                            <button type="submit">Submit</button>
                        </form>
                    )}

            </Formik>

    ) : <span>loading...</span>;

}

export default App;

1 Ответ

0 голосов
/ 03 февраля 2020

Вы должны использовать реквизиты name и render для компонента FieldArray. У вас также была опечатка при установке Costs вместо costs.

const renderFieldArray = (props: FormikProps<any>) => (arrayHelpers: any) => {
  return props.values.costs.map((x, index) => {
    return (
      <div key={index}>
        <input
          name={`costs.${index}.item`}
          value={method.name}
          onChange={props.handleChange}
        />
      </div>
    );
  });
};

<FieldArray name="costs" render={renderFieldArray(props)} />
...