我在react-final-form
中有一个带有sum
字段的对象数组。最后,我想计算所有款项的总数。因此,我像这样使用final-form-calculate
中的计算字段:
const calculator = createDecorator({
field: /day\[\d\]\.sum/, // when a field matching this pattern changes...
updates: (value, name, allValues) => {
console.log("Updated field", value, name);
// ...update the total to the result of this function
total: (ignoredValue, allValues) =>
(allValues.day || []).reduce((sum, value) => sum + Number(value || 0), 0);
return {};
}
});
当我在输入中输入值时,将调用console.log
,但总数不会更新。我猜它没有从必要字段中选择值。我该如何解决?这是我的密码箱https://codesandbox.io/s/react-final-form-calculated-fields-hkd65?fontsize=14。
答案 0 :(得分:1)
您的代码段中有一些语法错误,特别是计算器功能。此功能的该版本有效:
const calculator = createDecorator({
field: /day\[\d\]\.sum/, // when a field matching this pattern changes...
updates: {
// ...update the total to the result of this function
total: (ignoredValue, allValues) => (allValues.day || []).reduce((sum, value) => sum + Number(value.sum || 0), 0),
}
});
我做了两个主要更改,
Number(value || 0)
更改为Number(value.sum || 0)
updates
属性设置为对象而不是函数。答案 1 :(得分:1)
最终形式计算文档,说更新程序可以是:
更新程序函数的对象或生成函数的函数 更新多个字段。
在您的示例中,代码是它们之间的某种混合。另外,value.sum
包含输入的数字,而不是value
。
使用更新功能的对象,这是正确执行操作的方法:
const calculator = createDecorator({
field: /day\[\d\]\.sum/,
updates: {
total: (ignoredValue, allValues) => (allValues.day || []).reduce((sum, value) => sum + Number(value.sum || 0), 0)
}
});
或更新多个字段(实际上只是一个,但可能更多):
const calculator = createDecorator({
field: /day\[\d\]\.sum/,
updates: (ignoredValue, fieldName, allValues) => {
const total = (allValues.day || []).reduce((sum, value) => sum + Number(value.sum || 0), 0);
return { total };
}
});
此外,这是更新程序Typescript定义,以供参考:
export type UpdatesByName = {
[FieldName: string]: (value: any, allValues?: Object, prevValues?: Object) => any
}
export type UpdatesForAll = (
value: any,
field: string,
allValues?: Object,
prevValues?: Object,
) => { [FieldName: string]: any }
export type Updates = UpdatesByName | UpdatesForAll