【问题标题】:Adding values of redux-form field array添加redux-form字段数组的值
【发布时间】:2018-04-02 22:23:23
【问题描述】:

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

所以在表单状态中类似这种数据结构。

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

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

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

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);

甚至这个在返回

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

产生一个 TypeError: Cannot read property 'reduce' of undefined... 即使我可以看到

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

【问题讨论】:

    标签: reactjs redux redux-form


    【解决方案1】:
    const sum = arr.reduce((total, item) => total + Number(item.total), 0);
    

    arr.reduce 就是你要找的。​​p>

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

    【讨论】:

    • 对如何与 redux-form 集成有什么想法吗?
    • 添加了用例。我试图将其保持在最低限度以防止 TLDR。
    • 您需要像我在示例中所做的那样从状态中获取数组并减少它并返回值。
    • 所以这看起来可以工作,但返回 TypeError: Cannot read property 'reduce' of undefined。我有什么遗漏吗?
    • 是您传递数组的数据结构,它是空的吗?在减少之前添加此逻辑arr && arr.reduce'rest of code....'
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多