繁体   English   中英

使用 redux-form 上的字段数组计算总计和小计

[英]Calculated total and subtotal using field array on redux-form

使用代码,我将为您提供如何计算 redux 表单上的总计和小计?

    const calculatedSubtotal = (detail,quantity,price) =>{

     detail = [];

     const subtotals = [];

      detail.map((detailItem,index) =>{

               detailItem[index].quantity = quantity;

               detailItem[index].product.price = price;

         subtotals[index] = detailItem[index].quantity * detailItem[index].product.price;

        return subtotals[index];

           })

         } 

  const calculatedTotal = (detail,quantity,price) =>{

     detail = [];

      let total = 0;

       const subtotals = [];


        detail.map((detailItem,index) =>{

                detailItem[index].quantity = quantity;

               detailItem[index].product.price = price;
           subtotals[index] = detailItem[index].quantity * detailItem[index].product.price;

         total += subtotals[index];
         })

      return total;
  }


        componentDidUpdate(prevProps,prevState,snapShot){

          const {change} = prevProps;

          const {detail,quantity,price} = prevProps;

          if(this.props.detail !== prevProps.detail && this.props.quantity !== prevProps.quantity && 
                 this.props.price !== prevProps.price){

            change(`detail[${this.props.index}].subtotal`,calculatedSubtotal(detail,quantity,price));
              change('total',calculatedTotal(detail,quantity,price));
              }
        }


    const valueSelector = formValueSelector('bill');


      const makeStateToProps = () =>{

         const mapStateToProps = (state,props) =>{

                return {

                 detail: valueSelector(state, 
              `detail[${props.index}].quantity`,`detail[${props.index}].product.price`,
               `detail[${props.index}].subtotal`
               ),
                quantity: valueSelector(state,`detail[${props.index}].quantity`),
                price: valueSelector(state, `detail[${props.index}].product.price`)

            }

               }

              return mapStateToProps;
           }

我在上一篇文章中弄错了,因为我遗漏了两个参数:数量和价格。

更多信息可以在如何使用 formValueSelector 以 redux-form 计算总计和小计中找到

也许我正在注销我的函数calculatedSubtotal 和calculatedTotal 的输入

对你的details数组的形状做一些假设,你可以这样:

const cart = [
  {quantity: 1, product: {price: 5.00}},
  {quantity: 2, product: {price: 1.99}},
];

const calculatedSubtotal = (detail) => {
  return detail.map(detailItem => {
    return detailItem.quantity * detailItem.product.price;
  });
};

const calculateTotalFromSubtotal = subtotals => {
  return subtotals.reduce((grandTotal, itemSubtotal) => {
    return grandTotal + itemSubtotal;
  }, 0);
}

console.log(calculatedSubtotal(cart));
console.log(calculateTotalFromSubtotal(calculatedSubtotal(cart)));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM