【问题标题】:Formik and FieldArray Mapping with Typescript使用 Typescript 进行 Formik 和 FieldArray 映射
【发布时间】:2020-02-03 18:26:15
【问题描述】:

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

"TypeError: 无法读取未定义的属性 'map'"

这是初始值:

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

【问题讨论】:

  • 在 API 响应处理程序中,您有 Costs: response.data.costs 而不是 costs: response.data.costs。 (注意大写 C)。这只是问题中的错字,还是您的实际代码中的错字?
  • 我将代码替换为使用成本:response.data.costs。错误消失了,但该字段未呈现。

标签: reactjs typescript formik


【解决方案1】:

您应该为 FieldArray 组件使用 namerender 属性。您在设置 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)} />

【讨论】:

  • 感谢您提供的示例 sn-p。使用 sn-p 时出现此错误:“预期分配或函数调用,而是看到表达式 @typescript-eslint/no-unused-expressions”。
  • @TerryDoll,如果您不使用 arrayHelpers 变量,您可能需要删除它。
  • 我添加了:“arrayHelpers: any”,但我收到此错误:“找不到名称 'props'。”我怀疑这是因为 initialValues 是异步的?
  • @TerryDoll,我更新了答案以通过道具。
  • 感谢修改后的代码。我试过了,但出现以下错误:“参数'props'隐含地具有'any'类型。”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-03
  • 2021-08-31
  • 1970-01-01
  • 1970-01-01
  • 2019-03-05
相关资源
最近更新 更多