Math in Redux-form. Adding Fields together

2019-07-15 10:14发布

问题:

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.

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?

回答1:

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

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