Redux 形式的数学.将字段添加在一起

编程入门 行业动态 更新时间:2024-10-28 16:17:23
本文介绍了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.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 形式的数学.将字段添加在一起

本文发布于:2023-10-19 20:39:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1508705.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字段   形式   数学   Redux

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!