简体   繁体   English

无法使用反应 redux 从产品页面将商品添加到购物车

[英]not able to add items to cart from product page using react redux

I have listed out some products in product list page.我在产品列表页面列出了一些产品。 I am not able to add product in my cart.我无法在我的购物车中添加产品。 It is showing error in my reducer code.它在我的减速器代码中显示错误。 Here is my code.这是我的代码。

action行动

export const addToCart= id =>({
type: ADD_TO_CART,
id

}); });

reducer code减速机代码

const initialState = {
    products: [{id:1,title:'Dell Inspiron 3581', discount: 10, price:110,img:Image1},
    {id:2,title:'Dell Vostro 3362', discount: 10, price:80,img: Image2},
    {id:3,title:'Acer TravelMate', discount: 0,price:120,img: Image3},
    {id:4,title:'Lenovo ideapad core', discount: 15, price:260,img:Image4},
    {id:5,title:'Lenovo V145', discount: 0, price:160,img: Image5},
    {id:6,title:'Asus Zephyrus G14', discount: 5 ,price:90,img: Image6}],
    filteredProducts:[],
    cartItems:[],
    total:0,
    cartCount: 0
  };

export default function productReducer(state = initialState, action){
     switch(action.type){

       case ADD_TO_CART:
      const { cartItems, products, cartCount,total } = state;

      let productToAdd = cartItems.find(item=>item.id===action.id);
      let count;
      if (!productToAdd) {
        productToAdd = products.find(obj => obj.id === action.id);
        count = 1;
      } else {
        count = productToAdd.count + 1;
      }
      const pid = productToAdd.id;
      const newCart = { ...state.cartItems, [pid]: { ...productToAdd, count } };
      const newcount = cartCount + 1; 
      const newTotal = total+productToAdd.price
      return { ...state, cartItems: newCart, cartCount: newcount,total:newTotal};

        default:
            return state;
     }
}

here i am doing the count of added items if that product is already exist in cart then increase quantity of that product.如果购物车中已经存在该产品,那么我正在计算添加的项目,然后增加该产品的数量。 But i am getting type error because of null reference.但是由于 null 参考,我收到了类型错误。

TypeError: Unable to get property 'id' of undefined or null reference -> (const pid = productToAdd.id)类型错误:无法获取未定义或 null 参考的属性“id” -> (const pid = productToAdd.id)

Here is my productcomponent page:这是我的产品组件页面:

    import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import {addToCart} from '../../action/cartAction';
import {Button} from 'react-bootstrap';

class ProductComponent extends Component{
    constructor(props){
        super(props);
        this.state ={
            radioSearch : '',
            filteredData: this.props.products
        }
    }
    handleClick = (id)=>{
        this.props.addToCart(id); 
    }
    /** some other handler **/
    render(){
        let itemList = this.state.filteredData.map(item=>{
            return(
                <div className="card" key={item.id}>
                        <div className="card-image">
                            <img src={item.img} alt={item.title}/>
                            <span className="card-title">{item.title}</span>
                        </div>

                        <div className="card-content">
                            <p><b>Discount: {item.discount}%</b></p>
                            <p><b>Price: {item.price}$</b></p> <Button variant="dark" onClick={()=>{this.handleClick(item.id)}}>ADD TO CART</Button>
                        </div>
                 </div>

            )
        })

        return(
            <div className="container">
                /** some other code **/
                <div className="box">
                    {itemList}
                </div>
            </div>
        )
    }
}
const mapStateToProps = (state)=>{
    return {
        products: state.productReducer.products
    }
  }
function mapDispatchToProps(dispatch) {
return bindActionCreators({
    addToCart
}, dispatch);

export default connect(mapStateToProps,mapDispatchToProps)(ProductComponent)

here is my cartcomponent这是我的购物车组件

import React, { Component } from 'react';
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import {removeFromCart} from '../../action/cartAction';

class cartComponent extends Component {
    handleRemove(id){
        this.props.removeFromCart(id);
    }
    render() {
        console.log(this.props.cartItems.length);
        let cartProducts = this.props.cartItems.length ?
        (
            this.props.cart.map(item=>{
                return(

                    <li className="collection-item avatar" key={item.id}>
                                <div className="item-img"> 
                                    <img src={item.img} alt={item.img} className=""/>
                                </div>

                                <div className="item-desc">
                                    <span className="title">{item.title}</span>
                                    <p>{item.desc}</p>
                                    <p><b>Price: {item.price}$</b></p> 
                                    <p>
                                        <b>Quantity: {item.quantity}</b> 
                                    </p>
                                    <button className="waves-effect waves-light btn pink remove" onClick={()=>{this.handleRemove(item.id)}}>Remove</button>
                                </div>

                            </li>

                )
            })
        ):
        (
            <p>Your cart is empty</p>
        )
        return(
            <div className="container">
                <div className="cart">
                <h5>You have ordered:</h5>
                    <ul className="collection">
                        {cartProducts}
                    </ul>
                </div>
            </div>
        )
    }
}

function mapStateToProps(state) {
    return {
        cartItems : state.productReducer.cartItems
    }
}

function mapActionsToProps(dispatch) {
    return bindActionCreators({
        removeFromCart
    }, dispatch);
}


export default connect(mapStateToProps,mapActionsToProps)(cartComponent);

i have tried many things but it is not adding product to cart.我已经尝试了很多东西,但它没有将产品添加到购物车。 what are the changes needed to make it work?需要进行哪些更改才能使其发挥作用?

Here is my source code: source code这是我的源代码: 源代码

It looks like the way you map the action to props does not match the actual usage of the function.看起来你 map 对道具的动作与 function 的实际用法不匹配。

You map it like this:你 map 是这样的:

addToCart: (id)=>{dispatch(addToCart(id))}

The action just passes its parameter as payload meaning payload is equal to id :该操作只是将其参数作为payload传递,这意味着payload等于id

export const addToCart= payload =>({
  type: ADD_TO_CART,
  payload
});

But you expect the payload to be an object like this:但是您希望有效负载是 object,如下所示:

const { id } = action.payload;

You need to make them match.你需要让它们匹配。 Either pass the action an object:要么通过 object 的操作:

addToCart: (id)=>{dispatch(addToCart({id}))}

Or use the payload as the id:或者使用payload作为id:

const id = action.payload;

The result of the code as is, is that id is undefined, meaning no productToAdd .代码的结果是id未定义,这意味着没有productToAdd

In productReducer file you should push the item into state.cartItems在 productReducer 文件中,您应该将项目推送到 state.cartItems

if (!productToAdd) {
        productToAdd = products.find(obj => obj.id === action.id);
        count = 1;
     ADD row-> state.cartItems.push(productToAdd);
}

In this approach, if you don't enter a specified quantity of the product, it will be automatically placed to the cart as one item.在这种方法中,如果您没有输入指定数量的产品,它将作为一件商品自动放入购物车。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM