javascript - 在 React,Redux 应用程序中,我想使用选择器为对象数组中的每个对象计算小计 (price * qtyCount)
问题描述
我编辑了我的问题并添加了有问题的组件。我怀疑也许只是我不理解语法。
我当前在组件中的输出看起来像这样25.0018.00
,它应该是25.00
1 个对象和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);
解决方案
您将字符串数组传递给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,
});
推荐阅读
- firebase - Firebase 导出到 BigQuery 事件时间戳时区
- android - Android Studio - 安装失败。安装失败重新运行
- python - 为什么 setattr(super(), ...) 不等同于 super.__setattr__(...)?
- php - 如何修复数据库失败的连接
- jsonpath - JSON-Path 只返回单个字符而不是完整值
- r - 使用 group_map 将函数应用于分组小标题中的每个组
- java - 如何将 RGB 图像转换为 CIELUV 颜色空间?
- apache-storm - 风暴消息超时工作不正常
- c# - 列出解决方案文件夹中作为资源构建的 PNG 文件的所有路径
- sql - 身份规范