根据 redux Form 中的另一个字段验证一个字段

Validate one field based on another Field in redux Form

我正在使用 redux-form,我的组件有几个 FieldArray。 FieldArray 组件之一生成 table,如屏幕截图所示。这里每一行都是一个 Field 组件,包括复选框。我想要实现的是,如果选中该行上的 checkbox 组件,则只需要 price 字段。

我尝试使用 docs 中描述的 validate.js 来解决这个问题,但是因为这个组件的结构如下:

<FirstComponent>
<FieldArray
  component={SecondComponent}
  name="options"
  fruits={fruitsList}
 />
</FirstComponent>

在我的 SecondComponent 中,我正在迭代 fruitsList,如果长度大于 1,则渲染 ThirdComponent。该组件负责生成如屏幕截图所示的水果列表。有一定程度的嵌套,当我用值验证时,它有很多性能滞后,我的屏幕冻结直到它呈现 ThirdComponent。每个组件都有 Fields 位,因此无法轻松合并它们。以优雅的方式解决这个问题的任何更简单的方法都会有所帮助。验证逻辑如下:

props.fruitsList.map((fruit, index) => {
      const isChecked = values.getIn(['fruit', index, 'checked'])
      if (isChecked) {
        const price = values.getIn(['fruit', index, 'price'])
        if (price === undefined || price.length === 0) {
          errors.fruits[index] = { price: l('FORM->REQUIRED_FIELD') }
        }

      }
      return errors
    })

同步验证函数被赋予表单中的所有值。因此,假设您的复选框是一个表单值,您将拥有所需的所有信息。

function validate(values) {
  const errors = {}
  errors.fruits = values.fruits.map(fruit => {
    const fruitErrors = {}
    if (fruit.checked) { // only do fruit validation if it's checked
      if (!fruit.price) {
        fruitErrors.price = 'Required' // Bad user!!
      }
    }
    return fruitErrors
  })
  return errors
}

...

MyGroceryForm = reduxForm({
  form: 'groceries',
  validate
})(MyGroceryForm)