Redux-form字段数组:为数组项构建选择器并实现求和
解决方案:Redux-form字段数组求和选择器
当然可以!你完全不用手动逐个索引去取total值,直接获取整个test字段数组,再遍历求和就搞定了,这样不管数组有多少项都能自动适配,比硬编码索引灵活多了。
修改后的代码示例
const selector = formValueSelector('mainForm'); export const mapState = (state, ownProps) => { // 获取整个test字段数组 const testArray = selector(state, 'test'); // 计算所有项的.total字段总和,同时做空值容错 const totalSum = (testArray || []).reduce((accumulator, currentItem) => { // 确保currentItem和currentItem.total存在,避免出现NaN return accumulator + (currentItem?.total || 0); }, 0); return { totalSum }; };
关键说明
- 用
selector(state, 'test')直接拿到整个字段数组,而不是单个索引的项; - 用
(testArray || [])处理数组未定义的情况,避免调用reduce时报错; currentItem?.total || 0确保即使某个数组项没有total字段,也会用0代替,不会出现NaN;reduce方法高效遍历数组,累加所有total值,初始值设为0保证空数组时返回0。
这样你就可以把totalSum映射到组件的props里,直接显示在单独字段中啦。
内容的提问来源于stack exchange,提问作者Shawn Matthews
相关产品推荐
相关产品推荐

