reactjs - 使用 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;
解决方案
您应该为组件使用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)} />
推荐阅读
- list - 无法在 ValueListenableBuilder 中返回更新的小部件
- flutter - 在对象方法中颤振空安全条件
- verilog - always_latch 的复位信号的复位类型是什么?
- c++ - 类方法中的 Cout 什么都不做
- python - Coverage.py 只显示测试文件
- javascript - 多维数组;JavaScript; 算法
- reactjs - “警告:在列表中添加新元素时,列表中的每个孩子都应该有一个唯一的“关键”道具”
- c# - 带有 EF 网络核心的执行过程 Mysql
- javascript - lottie-player:有什么办法可以在动画加载后停止动画?
- python - 没有名为 (image_dehazer) 的模块