首页 > 解决方案 > 嵌套字段的 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;

标签: javascriptreactjsformsformik

解决方案


你有错误的初始值,应该是这样的:

[{ name: "Julia", age: "27" }]

相反,您传递了 2 个数组项


推荐阅读