我在用react从redux调用state时遇到了一些问题



嗨,我是react新手,我正在用redux制作简单的购物车应用程序,并进行react练习。我调用product api数据并将其保存在被称为产品的商店中,当用户点击按钮时;推车";。当我console.log(props.state.cart(向我显示用户单击的数据时,但如果我试图调用数据,它会向我显示映射不是函数的错误。

ProductList.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],
};
}

最新更新