javascript - 嵌套字段的 Formik 字段数组
问题描述
我想在组件内呈现带有嵌套字段的表单<FieldArray />
。但是当我基于索引创建表单字段时,我得到了我不想要的额外字段。如下所示:
如您所见,Julia 和 28 应该在同一行。但相反,我得到了两行中的四个字段。键入时,空字段也会写入年龄和姓名值。我不明白为什么会这样。但我不想要它们。您可以在下面看到该组件的代码。我还在这里创建了一个沙箱来处理它codesandbox。
注意:我想要这些嵌套字段,因此我的数组结构对friends: [{ name: "Julia" }, { age: "28" }]
问题很重要。
import React from "react";
import { Formik, Form, Field, FieldArray } from "formik";
// Here is an example of a form with an editable list.
// Next to each input are buttons for insert and remove.
// If the list is empty, there is a button to add an item.
const FriendList = () => (
<div>
<h1>Friend List</h1>
<Formik
initialValues={{ friends: [{ name: "Julia" }, { age: "28" }] }}
onSubmit={values =>
setTimeout(() => {
alert(JSON.stringify(values, null, 2));
}, 500)
}
render={({ values }) => (
<Form>
<FieldArray
name="friends"
render={arrayHelpers => (
<div>
{values.friends.map((friend, index) => (
<div key={index}>
<Field name={`friends[${index}].name`} />
<Field name={`friends.${index}.age`} />
<button
type="button"
onClick={() => arrayHelpers.remove(index)}
>
-
</button>
</div>
))}
<button
type="button"
onClick={() => arrayHelpers.push({ name: "", age: "" })}
>
+
</button>
</div>
)}
/>
<pre>{JSON.stringify(values, null, 2)}</pre>
</Form>
)}
/>
</div>
);
export default FriendList;
解决方案
你有错误的初始值,应该是这样的:
[{ name: "Julia", age: "27" }]
相反,您传递了 2 个数组项
推荐阅读
- r - 使用 system() 在后台运行闪亮的应用程序时出错?
- javascript - 如何从 node.js 重新加载浏览器
- javascript - JavaScript 创建二维数组
- json - 解析来自 Postman 的 JSON 数据
- r - ggplot2:点颜色不会自动更改
- javascript - XMLHttpRequest() 发送空有效载荷
- svg - svg 字体有连字表吗?
- python - pydantic 转换为 jsonable dict(不是完整的 json 字符串)
- linux - 新 git 用户的授权键被忽略
- javascript - 如何在 React 应用程序中使用 Fetch 向 Flask API 发送 POST 请求