javascript - 在 React,Redux 应用程序中,我想使用选择器计算对象数组中每个对象的小计(价格 * qtyCount)

标签 javascript reactjs redux

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

我当前在组件中的输出如下所示 25.0018.00,对于 1 个对象,它应该是 25.00,对于下一个对象应该是 18.00

我有一个如下所示的对象数组:

Json:

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

最佳答案

您正在将字符串数组传递给 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,
});

关于javascript - 在 React,Redux 应用程序中,我想使用选择器计算对象数组中每个对象的小计(价格 * qtyCount),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59849860/

相关文章:

javascript - React-网络摄像头录制、重放、重新录制、存储

android - React Native - 定位的绝对 View 位于屏幕的其他组件后面

reactjs - 自动重新获取不起作用 - RTK 查询

javascript - 编辑 json 对象中某些字段的更好方法?

javascript - 传递给输入字段的复选框在 jquery 中有冲突

javascript - 取消隐藏/隐藏文本后如何防止滚动到顶部?

javascript - 两个用于滑动相同 div 但方式不同的按钮(从右到左和从左到右)

javascript - 带有嵌套 if 的 else 语句

ReactJS Material UI withStyles incl。 TS 中的主题

reactjs - 无法处理 Uncaught TypeError : Cannot read property 'location' of undefined at createRouterReducer