You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

redux-form中<FieldArray>结合<FormSection>处理复杂对象数组遇阻

解决redux-form中FieldArray嵌套FormSection的问题

我之前也碰到过一模一样的情况——所有表单值都塞到rule键下面,而不是rules数组里的每个对象中。核心问题其实是FormSection的name属性没有和FieldArray的数组索引绑定,导致所有字段都指向了同一个路径,而不是数组的对应元素。

下面是我验证过的可行实现方式,你可以参考:

核心思路

  1. 用FieldArray管理整个数组字段(比如name="rules")
  2. 在FieldArray的渲染函数中,遍历数组元素时,给每个FormSection设置name={index},这样FormSection内部的字段会自动挂载到rules[index]这个对象下
  3. FormSection内部的Field组件直接使用对象的属性名作为name即可

完整代码示例

import React from 'react';
import { Field, FieldArray, FormSection, reduxForm } from 'redux-form';

// 单个规则的表单组件,用FormSection包裹
const RuleFormSection = () => (
  <FormSection>
    <div>
      <label>条件</label>
      <Field name="condition" component="input" type="text" placeholder="输入条件" />
    </div>
    <div>
      <label>动作</label>
      <Field name="action" component="input" type="text" placeholder="输入动作" />
    </div>
    <hr />
  </FormSection>
);

// 主表单组件
const RulesForm = ({ handleSubmit, fields }) => (
  <form onSubmit={handleSubmit}>
    <h3>规则列表</h3>
    {/* FieldArray管理rules数组 */}
    <FieldArray name="rules">
      {({ fields }) => (
        <div>
          {/* 遍历数组,每个元素对应一个RuleFormSection */}
          {fields.map((rule, index) => (
            <div key={index}>
              {/* 关键:给FormSection设置name为当前索引 */}
              <FormSection name={index}>
                <RuleFormSection />
              </FormSection>
              <button
                type="button"
                onClick={() => fields.remove(index)}
              >
                删除规则
              </button>
            </div>
          ))}
          <button
            type="button"
            onClick={() => fields.push({})}
          >
            添加新规则
          </button>
        </div>
      )}
    </FieldArray>
    <button type="submit">提交</button>
  </form>
);

export default reduxForm({
  form: 'rulesForm' // 表单唯一标识
})(RulesForm);

为什么这样能解决问题?

  • FieldArray的name="rules"告诉redux-form我们要管理一个名为rules的数组字段
  • 每个FormSection name={index}相当于把内部字段的路径设置为rules[index].xxx,这样每个规则的字段都会被存入数组对应的对象中,而不是共享同一个rule键
  • 提交后你会得到类似这样的结构:
    {
      "rules": [
        { "condition": "条件1", "action": "动作1" },
        { "condition": "条件2", "action": "动作2" }
      ]
    }
    

如果还有问题,可以检查一下redux-form的版本(确保是v7+,因为FormSection在旧版本可能有差异),或者确认FieldArray和FormSection的name属性是否正确传递。

内容的提问来源于stack exchange,提问作者axelav

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 04:30:40