添加 redux-form 字段数组的值

Adding values of redux-form field array

对于 FieldArray 中的每个新项目,我希望将 FieldArray 中名为 total 的 Field 的内容加在一起。

所以像这样的数据结构在表单状态中是明智的。

test.0.total + test.1.total + test.2.total = testTotal

我不确定访问表单中数据的选项是什么。如果我专门列出预期的字段,formValueSelector 会很好用,但考虑到这是一个 FieldArray,我不知道在任何给定时间会有多少项。我将如何循环数组结构以添加这些字段?

我目前正在使用看起来像这样的选择器 return 数组。

const selector = formValueSelector('mainForm');
      export const mapState = (state, ownProps) => {
        const Total = selector(state, 'test');
        return { Total };
      }

我怎样才能在选择器中构建循环机制?

类似这样的东西...,但不是动态的。

    const selector = formValueSelector('mainForm');
      export const mapState = (state, ownProps) => {
        const test1 = selector(state, 'test.0.total');
        const test2 = selector(state, 'test.1.total');
        const test3 = selector(state, 'test.2.total');
       return { test1, test2, test3, 
        total: test1 + test2 + test3 };
      }

添加这样的东西....

const test = selector(state, "test");
const sum = test.reduce((total, item) => total + Number(item.total), 0);

甚至 return

sum: test.reduce((total, item) => total + Number(item.total), 0);

产生类型错误:无法读取未定义的 属性 'reduce'... 即使我可以看到

我可以看到数组在状态中不是未定义的...有没有办法解决这个问题?

const sum = arr.reduce((total, item) => total + Number(item.total), 0);

arr.reduce 就是您要找的。

如果您的数据结构不包含具有 item.total 的对象,则将该部分替换为 item