我正在尝试使用formik <FieldArray />
,在这里我可以使用push
arrayHelper来填充数组数据。在example中,他们正在直接从按钮创建表单。但是我想提取它以使用useCallback
这是我的主意
import React, { useCallback } from "react";
import { useField, FieldArray } from "formik";
import { Button } from "@material-ui/core";
import { FormikTextField, formStyles } from "./Utils";
function WitnessChild({ remove, push }) {
const classes = formStyles();
const [field] = useField("witnesses");
const handleAdd = useCallback(
() =>
push({
FirstName: "",
LastName: "",
AddressStreet: "",
AddressSuburb: "",
AddressPostcode: "",
Mobile: ""
}),
[field.value]
);
return (
<>
{field.value.length > 0 &&
field.value.map((witness, index) => (
<div>
<div className={`${classes.margin} row`}>
<Button
variant="contained"
component="label"
className={`${classes.instructions}`}
onClick={handleAdd}
>
Add New
</Button>
</div>
<div className={`${classes.margin} row`}>
<div className="col-6">
<FormikTextField
className={`${classes.instructions}`}
id={`witnesses.${index}.FirstName`}
name={`witnesses.${index}.FirstName`}
label="First Name"
/>
</div>
<div className="col-6">
<FormikTextField
className={`${classes.instructions}`}
id="witnessLastName"
name="witnessLastName"
label="Last Name"
/>
</div>
</div>
<div className={`${classes.margin} row`}>
<div className="col-6">
<FormikTextField
className={`${classes.instructions}`}
id="witnessAddressStreet"
name="witnessAddressStreet"
label="Street"
/>
</div>
<div className="col-6">
<FormikTextField
className={`${classes.instructions}`}
id="witnessAddressSuburb"
name="witnessAddressSuburb"
label="Suburb"
/>
</div>
</div>
<div className={`${classes.margin} row`}>
<div className="col-6">
<FormikTextField
className={`${classes.instructions}`}
id="witnessAddressPostcode"
name="witnessAddressPostcode"
label="Postcode"
/>
</div>
<div className="col-6">
<FormikTextField
className={`${classes.instructions}`}
id="witnessMobile"
name="witnessMobile"
label="Mobile"
/>
</div>
</div>
</div>
))}
</>
);
}
export default function WitnessDetails() {
return <FieldArray name="witnesses" render={WitnessChild} />;
}
我不确定为什么会返回:
× 错误:无效的挂钩调用。挂钩只能在功能组件的主体内部调用。可能由于以下原因之一而发生: 1.您的React和渲染器版本可能不匹配(例如React DOM) 2.您可能违反了《钩子规则》 3.您可能在同一应用程序中拥有多个React副本 有关如何调试和解决此问题的提示,请参见链接。
我实际上可以通过在按钮() => {}
内创建handleAdd func来消除此错误,但是我认为这不是一个好习惯,因为它将每次都启动。谁能告诉我提取这种钩子的最佳实践是什么?
谢谢