Redux 形式的数学.将字段添加在一起 [英] Math in Redux-form. Adding Fields together

查看:44
本文介绍了Redux 形式的数学.将字段添加在一起的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用选择器以 redux 形式将多组字段添加在一起.

I'm trying to add several sets of fields together in a redux-form using selectors.

目前我是这样做的...

Currently I'm doing it like this...

componentDidUpdate(prevProps) {
    let total = (Number(this.props.tradeInTotal) + Number(this.props.thirdPartyEquipmentTotal));
    if(
      this.props.equipmentTotal != prevProps.equipmentTotal || 
      this.props.softwareTotal != prevProps.softwareTotal ||
      this.props.thirdPartyEquipmentTotal != prevProps.thirdPartyEquipmentTotal ||
      this.props.miscTotal != prevProps.miscTotal ||
      this.props.tradeInTotal != prevProps.tradeInTotal
    ){
      this.props.dispatch(change('mainForm', 'totalPurchase', total));
    }
  }

这不是特别可重复的,从样板的角度来看是非常可怕的.

This isn't particularly repeatable, and is super hideous from a boilerplate perspective.

我还有一个奇怪的问题,直到有多个小计中有一个数字后才会开始计算(这可以通过将初始值设置为 0 来补救,但这会增加更多样板)任何人在 redux-form 中添加字段有更好的解决方案吗?

I also have a strange issue in that this doesn't start calculating until more than one of the subtotals has a number in it (this might be remedied by setting an initial value of 0, but that adds even more boilerplate) anyone have a better solution to adding fields in redux-form?

推荐答案

如果所有 props 都与计算 total 相关,你可以使用 Array.reduce.例如:

If all of the props are to do with calculating the total, you could use Array.reduce. For example:

componentDidUpdate () {
  const total = Object.values(this.props)
    .reduce((total, value) => total + value, 0)

  if (/* new total differs from total in the store */) {
    this.props.dispatch(change('mainForm', 'totalPurchase', total));
  }
}

如果有额外的props需要省略,在总结前使用Object.entriesArray.filter:

If there are additional props that need to be omitted, use Object.entries and Array.filter before summing up:

componentDidUpdate () {
  const totalKeys = ['equipmentTotal', 'softwareTotal', ...]
  const total = Object.entries(this.props)
    .filter(([key, value]) => totalKeys.includes(key)) // filter out non-relevant props
    .reduce((total, [key, value]) => total + value, 0)

  if (/* new total differs from total in the store */) {
    this.props.dispatch(change('mainForm', 'totalPurchase', total));
  }
}

这篇关于Redux 形式的数学.将字段添加在一起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆