我正在尝试使用选择器以 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.entries和Array.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 形式的数学.将字段添加在一起
发布评论