Apa*_*esh 6 reactjs redux-form
我使用的是redux-form,我的Component有几个FieldArray.其中一个FieldArray组件生成表格,如屏幕截图所示.这里每行都是一个Field包含复选框的组件.我想要实现的是,如果checkbox检查该行上的组件,则只price需要字段.
我尝试使用docs中validate.js描述的方法解决这个问题,但是因为这个组件的结构如下:
<FirstComponent>
<FieldArray
component={SecondComponent}
name="options"
fruits={fruitsList}
/>
</FirstComponent>
Run Code Online (Sandbox Code Playgroud)
在我的SecondComponent迭代中fruitsList,如果长度大于1,那么我渲染ThirdComponent.该组件负责生成屏幕截图中显示的Fruit列表.有一定程度的嵌套,当我用值验证时,它有很多性能滞后,我的屏幕冻结,直到它呈现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
})
Run Code Online (Sandbox Code Playgroud)
![表格Sceenshot]](https://i.stack.imgur.com/WErAV.png)
同步验证函数被赋予表单中的所有值。因此,假设您的复选框是一个表单值,您就拥有了所需的所有信息。
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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1588 次 |
| 最近记录: |