嗨,我是新来的人,我正在用redux制作简单的购物车应用程序,并进行练习。然后我调用prouduct api数据并将其保存在称为产品的商店中,当用户单击按钮时,应将其保存为“购物车”状态。当我console.log(props.state.cart)向我显示用户单击的数据时,但是如果我尝试调用该数据,则向我显示错误地图不是函数。
产品清单.js
import React, { useEffect } from "react";
import { getAllProducts, getCartList } from "../../../actions/postActions";
import { connect } from "react-redux";
import PropTypes from "prop-types";
import { AddToCartButton } from "./AddToCartButton";
// import ShoppingCart from "../shoppingCart.js/ShoppingCart";
const ProductList = (props) => {
useEffect(() => {
props.getAllProducts();
}, []);
// when I console.log it shows the data which user clicked.
console.log(props.cartList);
const addToCart = async (item) => {
props.getCartList(item);
};
return (
<div>
{props.products.map((x) => (
<div key={x.id}>
<img className="productImg" src={x.image} alt={x.title} />
<h4>{x.title}</h4>
<p>{x.price}€</p>
<button onClick={() => addToCart(x)}>test cart</button>
<AddToCartButton />
</div>
))}
<div>
{props.cartList &&
props.cartList.map((x) => <li key={x.id}>{x.title}</li>)}
</div>
</div>
);
};
ProductList.propTypes = {
getAllProducts: PropTypes.func.isRequired,
products: PropTypes.array.isRequired,
getCartList: PropTypes.func.isRequired,
cartList: PropTypes.array.isRequired,
};
const mapStateToProps = (state) => ({
products: state.items.allItems,
cartList: state.items.cart,
});
export default connect(mapStateToProps, { getAllProducts, getCartList })(
ProductList
);
postReducer.js
import { FETCH_PRODUCTS, SHOPPING_CART, AMOUNT, USERS } from "../actions/types";
const initialState = {
allItems: [],
cart: [],
amount: 3,
};
export default function (state = initialState, action) {
console.log(action.payload);
//output: list of allItems and object of cart item which user clicked
switch (action.type) {
case FETCH_PRODUCTS:
return {
...state,
allItems: action.payload,
};
case SHOPPING_CART: {
return {
...state,
cart: action.payload,
};
}
case AMOUNT: {
return {
...state,
amount: state.amount,
};
}
default:
return state;
}
}
在减速器中尝试以下操作:
case SHOPPING_CART: {
return {
...state,
cart: [action.payload,...state.cart],
};
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句