我正在使用React和经典的Redux简单的电子商务服务。我有从购物车中删除项目的问题。当我点击一个产品所附的按钮删除它从购物车中删除所有元素。
在我看来,代码是正确的,我比较了它与其他几个解决方案,我发现了所以。我很高兴为任何提示。
下面是我的代码:
初始状态
initialState: {
cart: {
products: [],
},
}
具有删除功能的购物车中的产品(此处的props是具有产品详细信息的对象)
const ProductInCart = (props) => {
const dispatch = useDispatch();
const productId = props.id;
console.log(productId)
const handleDelete = e => {
e.preventDefault();
dispatch(deleteProduct(productId))
}
return (
<div className={styles.product__item}>
<Link to={`/product/${props.id}`} className={styles.link}>
<div className={styles.leftColumn}>
<img
src={`${process.env.PUBLIC_URL}${props.img}`}
alt="Product image"
/>
<div className={styles.info}>
<h3>{props.title}, {props.width} cm x {props.height} cm</h3>
<p>Color: {props.color}</p>
</div>
</div>
</Link>
<div className={styles.rightColumn}>
<div className={styles.delete} onClick={handleDelete}>
<DeleteIcon className={styles.icon}/>
<span>Delete</span>
</div>
<div className={styles.quantity}>
<h2>Quantity:</h2>
<Quantity />
</div>
<span className={styles.price}>${props.price}</span>
</div>
</div>
)
}
这是我的减速器
// selectors
export const getAll = ({ cart }) => cart.products;
export const getCount = ({ cart }) => cart.products.length;
// action name creator
const createActionName = actionName => `app/cart/${actionName}`;
// action types
const ADD_PRODUCT = createActionName('ADD_PRODUCT');
const DELETE_PRODUCT = createActionName('DELETE_PRODUCT');
// action creators
export const addProduct = payload => ({ payload, type: ADD_PRODUCT});
export const deleteProduct = payload => ({ payload, type: DELETE_PRODUCT});
// reducer
const cartReducer = (statePart = [], action ={}) => {
switch (action.type) {
case ADD_PRODUCT: {
return {
...statePart,
products: [...statePart.products, action.payload]
}
}
case DELETE_PRODUCT: {
return statePart.products.filter(product => product.id !== action.payload)
}
default:
return statePart;
}
}
export default cartReducer;
1条答案
按热度按时间ddhy6vgd1#
应该返回一个新状态,如ADD_PRODUCT案例