首页 > 解决方案 > 在 React,Redux 应用程序中,我想使用选择器为对象数组中的每个对象计算小计 (price * qtyCount)

问题描述

我编辑了我的问题并添加了有问题的组件。我怀疑也许只是我不理解语法。

我当前在组件中的输出看起来像这样25.0018.00,它应该是25.001 个对象和18.00下一个对象。

我有一组看起来像这样的对象:

杰森:

counters: [
    {
      id: "lam1g8uzn",
      windowType: "First ",
      windowLocation: "Out",
      price: 5,
      qtyCount: 5,
      imgUrl:'long string'
    },
    {
      id: "r5hamynf3",
      windowType: "Second ",
      windowLocation: "In",
      price: 2,
      qtyCount: 9,
      imgUrl: 'long string'
    }
]

这是我的选择器

  const selectCounter = (state) => state.counter;

  export const selectCounterItems = createSelector(
   [selectCounter],
   (counter) => counter.counters,
  );

这是有问题的选择器

  export const selectCounterSubtotal = createSelector(
      [selectCounterItems],
      (counters) => counters.map((counter) => (
      (counter.qtyCount * counter.price).toFixed(2)
    )),
  );

这是我显示小计的组件

 import { connect } from 'react-redux';
 import { createStructuredSelector } from 'reselect';
 import { selectCounterSubtotal } from '../../redux/counter/counter- 
 selectors';

 const SubTotalDisplay = ({ subTotal }) => (
  // const subtotal = (qty * price).toFixed(2);
  <div className="subtotal-diaplay">
  <span> Subtotal $</span>
  <span className="subtotal">{subTotal}</span>
  </div>
 );

 const mapStateToProps = createStructuredSelector({
  subTotal: selectCounterSubtotal,
 });

export default connect(mapStateToProps, null)(SubTotalDisplay);

标签: javascriptreactjsredux

解决方案


您将字符串数组传递给SubtotalDisplay. 当 React 获得一个数组节点时,它会渲染数组中的每个项目。这就是你得到“25.0018.00”的原因。

考虑更新SubtotalDisplay组件以呈现传递给它的所有小计:

const SubTotalDisplay = ({ subTotals }) => (
  subTotals.map((subTotal, index) => (
    <div className="subtotal-display" key={index}>
      <span> Subtotal $</span>
      <span className="subtotal">{subTotal}</span>
    </div>
  ))
);

const mapStateToProps = createStructuredSelector({
  subTotals: selectCounterSubtotal,
});

推荐阅读