【发布时间】:2021-09-28 15:21:52
【问题描述】:
当我添加来自同一产品的新商品时,如何让我的购物车更好地工作用户可以增加产品的数量而不是将其添加到购物车中。
这是我的减速器的代码:
import {ADD_TO_CART, REMOVE_FROM_CART, CLEAR_CART} from '../constants';
const initialState = {
cartItems: [],
totalPrice: 0,
};
const cartItems = (state = initialState, action: any) => {
switch (action.type) {
case ADD_TO_CART:
return {
...state,
cartItems: [...state.cartItems, action.payload],
totalPrice: state.totalPrice + action.payload.price,
};
case REMOVE_FROM_CART:
return {
...state,
cartItems: state.cartItems.filter(
cartItem => cartItem !== action.payload,
),
totalPrice: state.totalPrice - action.payload.price,
};
case CLEAR_CART:
return {...initialState};
}
return state;
};
export default cartItems;
我尝试这样做,但失败了
import {ADD_TO_CART, REMOVE_FROM_CART, CLEAR_CART} from '../constants';
const initialState = {
cartItems: [],
totalPrice: 0,
};
const cartItems = (state = initialState, action: any) => {
switch (action.type) {
case ADD_TO_CART:
const theItem = state.cartItems.find(
product => product.name === action.payload.name,
);
if (theItem) {
return {
...state,
cartItems: [...state.cartItems, action.payload],
totalPrice: state.totalPrice + action.payload.price,
qty: theItem.qty + 1,
};
}
return {
...state,
cartItems: [...state.cartItems, action.payload],
totalPrice: state.totalPrice + action.payload.price,
};
case REMOVE_FROM_CART:
return {
...state,
cartItems: state.cartItems.filter(
cartItem => cartItem !== action.payload,
),
totalPrice: state.totalPrice - action.payload.price,
};
case CLEAR_CART:
return {...initialState};
}
return state;
};
export default cartItems;
我认为没有必要分享操作,因为购物车 100% 运行良好,但我会分享,
import {ADD_TO_CART, REMOVE_FROM_CART, CLEAR_CART} from '../constants';
export const addToCart = (payload: any) => {
return {
type: ADD_TO_CART,
payload,
};
};
export const removeFromCart = (payload: any) => {
return {
type: REMOVE_FROM_CART,
payload,
};
};
export const clearCart = () => {
return {
type: CLEAR_CART,
};
};
最后是带有有效负载的屏幕
const product = {
id: 1,
name: 'LAptop',
price: 1000,
qty: 0,
// imgURL:
// 'https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_160x56dp.png',
};
....
<Button
title="Add 1"
onPress={() => {
dispatch(addToCart(product));
console.log(cartData);
}}
/>
....
【问题讨论】:
-
您通常将商品数量存储在哪里,或者这是问题所在,您不是?什么是动作有效载荷?你能分享你的动作创建者以及它们是如何使用的吗?
标签: javascript reactjs react-native redux react-redux