redux-form用对象数组初始化FieldArray

时间:2018-04-02 20:50:42

标签: reactjs redux redux-form

我检查了FieldArray的示例,所有搜索/问题都指向将简单数组作为初始化程序传递。但是,如果数组由对象组成,我不确定如何使Field显示初始值。

const renderFields = ({ fields, command }) => fields.map((name, index, fields) => {
  const { type, component } = getRenderer(command, name)
  const { fieldDescription, fieldName } = fields.get(index)
  return <Field key={`${name}.${fieldName}`} name={`${name}.${fieldName}`} type={type} component={component} label={fieldDescription} />
})

// usage

const Command = ({ command }: Props) => (
  <div className="command">
    <FieldArray name={`${command}.fields`} component={renderFields} command={command} />
  </div>
)

initialValues看起来像:

{
  id: 'some identifier',
  abc: { include: true, fields: [{fieldDescription, fieldName, value }, ...]
  def: { include: true, fields: [{fieldDescription, fieldName, value }, ...]  
}

abcdefcommand传递给renderFields

1 个答案:

答案 0 :(得分:0)

想出来 - 诀窍是不要使用FieldArray

const renderMembers = ({ fieldDefs, command }) => {
  const fields = fieldDefs[command].members
  return (
    <FormSection key={i} name={`${c}`}>
      {fields.map((member, index) => {
        const name = `members.${member.name}`
        return (
            <Field
              key={index}
              name={name}
              type="text"
              component={renderField}
              label={member.label}
            />            
        )
      })}
    </FormSection>
  )
}


const Command = ({ command }: Props) => (
  <div className="command">
    {renderMembers({fieldDefs, key: c})}
  </div>
)

完全正常的例子:CodeSandbox