【发布时间】:2018-12-29 19:50:13
【问题描述】:
您好,我的 redux 应用目前正在添加购物车商品,但我想计算总价。
如何在 redux 中做到这一点?
目前我的 Reducer 看起来像这样。
const cartItems = (state = [], action) => {
switch (action.type)
{
case 'ADD_TO_CART':
// console.log('CarItems.JS', action.payload)
if (state.some(cartItem => cartItem.id === action.payload.id)) {
// increase qty if item already exists in cart
return state.map(cartItem => (cartItem.id === action.payload.id ? { ...cartItem, qty: cartItem.qty + 1 } : cartItem));
}
return [...state, { ...action.payload, qty: 1 }]; // else add the new item to cart
case 'REMOVE_FROM_CART':
return state
.map(cartItem => (cartItem.id === action.payload.id ? { ...cartItem, qty: cartItem.qty - 1 } : cartItem))
.filter(cartItem => cartItem.qty > 0);
}
return state
}
export default cartItems
解决方案
计算总和并返回。
const mapStateToProps = (state) => {
let totalPrice = 0;
state.map((item) => {
totalPrice += item.price * item.qty;
});
return {
cartItems: state,
totalPrice : totalPrice
}
}
在视图中调用它
<Text style={styles.total}>Totaal: € {this.props.totalPrice}</Text>
【问题讨论】:
标签: redux react-redux