我需要访问我当前的购物车状态,这只是具有以下功能的产品的列表 已添加到购物车中,以便我检查ID以计算重复产品的数量。我意识到这里的问题之一是我已经用一个空数组初始化了itemsInCart,但是我不确定在这里还要做什么,因为没有它就无法破坏状态。
cartReducer.js
const itemsInCart = []
export const cartReducer = (state = itemsInCart, action) => {
const { type, payload } = action;
switch (type) {
case "ADD_TO_CART":
return [
...state,
{
imgUrl: payload.imgUrl,
name: payload.name,
price: payload.price,
quantity: payload.quantity
},
];
default:
}
return state;
};
Product.js
点击该按钮将分派“ ADD_TO_CART”操作,并将新产品添加到处于状态的购物车中。
import React from 'react';
import {useDispatch} from 'react-redux';
const Product = ({imgUrl, name, price, id }) => {
const dispatch = useDispatch()
const addToCart = () => {
dispatch({
type: "ADD_TO_CART",
payload: {
imgUrl: imgUrl,
name: name,
price: price,
id: id
}
})
}
return (
<div
key={id}
style={{
textAlign: "center",
display: "flex",
border: "1px solid",
marginBottom: "2rem",
flexDirection: 'column'
}}
>
<img
src={imgUrl}
style={{ height: "5rem", width: "5rem" }}
alt="The product"
/>
<h3>{name}</h3>
<p>${price}.00</p>
{id}
<button onClick={()=>addToCart()}>Add To Cart</button>
</div>
);
}
export default Product;
InCartList.js
在CartContainer中渲染购物车中的物品列表
import React from "react";
import { useSelector } from "react-redux";
import CartItem from "./CartItem";
const ProductList = () => {
const allState = useSelector((state) => state.cart);
const renderProducts = () => {
return allState.map((product) => {
return (
<CartItem id={product.id} quantity={product.quantity}key={product.id} name={product.name} price={product.price}/>
);
});
};
return <>{renderProducts()}</>;
};
export default ProductList;
答案 0 :(得分:0)
您不应该在reducer内放置任何逻辑(reducer应该仅是纯函数)
您可以尝试在调度操作 ADD_TO_CART
之前获取所需的状态export const store = configureAppStore(history);