首页 > 解决方案 > 使用 Typescript 进行 Formik 和 FieldArray 映射

问题描述

我是 React 和 Formik 的新手,仍在尝试学习如何使用它。我正在尝试从一组项目中映射项目。但是,我不确定映射的正确语法是什么。我收到以下错误:

“TypeError:无法读取未定义的属性‘地图’”

这是初始值:

{
    "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;

标签: reactjstypescriptformik

解决方案


您应该为组件使用namerender道具。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)} />

推荐阅读