无法在reactjs购物车中添加项目

无法在reactjs购物车中添加项目,reactjs,redux,Reactjs,Redux,我已经在react和redux中创建了一个购物车。但是,我面临的问题是,我无法将商品添加到购物车中 下面是我的代码 action.js import axios from 'axios'; export const GET_NAVBAR = "GET_NAVBAR"; export const GET_PRODUCTS = "GET_PRODUCTS"; export const GET_PRODUCT_DETAIL = "GET_PRODUCT_DETAIL"; export const A

我已经在react和redux中创建了一个购物车。但是,我面临的问题是,我无法将商品添加到购物车中

下面是我的代码

action.js

import axios from 'axios';

export const GET_NAVBAR = "GET_NAVBAR";
export const GET_PRODUCTS = "GET_PRODUCTS";
export const GET_PRODUCT_DETAIL = "GET_PRODUCT_DETAIL";
export const ADD_CART = "ADD_CART";
export const REMOVE_CART = "REMOVE_CART"

export const BASE_API_URL = "http://localhost:3030";


export const getNavbar = () => {
    return axios.get(BASE_API_URL + '/topCategory').then(res => {
        return {
            type: GET_NAVBAR,
            payload: res.data.express.catalogGroupView
        };
    });
};

export const getProducts = (id) => {
    return axios.get(BASE_API_URL + '/category/'+id).then(res => {
        return {
            type: GET_PRODUCTS,
            payload: res.data.express.catalogEntryView
        };
    });
};

export const getProductDetail = (id) => {
    return axios.get(BASE_API_URL + '/product/'+id).then(res => {
        return {
            type: GET_PRODUCT_DETAIL,
            payload: res.data.express.catalogEntryView
        };
    });
};

export function addToCart(item) {
    return {
        type: 'ADD',
        item: item
    };
  }

  export function removeFromCart(item) {
    return {
        type: 'REMOVE',
        item: item
    };
  }
在reducer文件夹中,我使用了两个js文件-

index.js

import { combineReducers } from "redux";
import fashion from "./fashionReducer";
export const rootReducer = combineReducers({
    fashion: fashion
});
fashionReducer.js

import {GET_NAVBAR, GET_PRODUCTS} from "../actions";
import {GET_PRODUCT_DETAIL} from "../actions/index";
import {ADD_CART} from "../actions/index";
import {REMOVE_CART}from "../actions/index";

const INITIAL_STATE = {navbar: [], products: [], productDetail:[], cartDetail:[]};

export default function (state = INITIAL_STATE, action) {
    switch (action.type) {
        case GET_NAVBAR:
            return {
                ...state,
                navbar: action.payload
            };
        case GET_PRODUCTS:
            return {
                ...state,
                products: action.payload
            };
        case GET_PRODUCT_DETAIL:
            return {
                ...state,
                productDetail: action.payload
            };

        case ADD_CART:
        return{
            ...state,
            cartDetail: action.payload
        };

        case REMOVE_CART:

        const firstMatchIndex = state.indexOf(action.payload)
        return state.filter((item, index) => index!==firstMatchIndex) 

        default:
            return state;
    }
}
在下面的代码中,我有一个产品列表和一个按钮要添加到购物车中

PDP.js

import React, {Component} from "react";
import {Route, Link, BrowserRouter} from "react-router-dom";

import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';
import {getProductDetail} from "../actions";
import { addToCart } from '../actions/index';


class PDP extends Component {

    componentDidUpdate(prevProps) {
        let currentId = this.props.match.params.id;
        let previousId = prevProps.match.params.id;
        if (currentId !== previousId) {
            this.props.getDetails(currentId);
        }
    }

    componentDidMount() {
        let {id} = this.props.match.params;
        this.props.getDetails(id);
    }

    render() {
        const {productDetail} = this.props;

        const picUrl = "https://149.129.128.3:8443";
        return (
            <div>
                <div className="container">
                    <div className="row">
                        {productDetail &&
                        productDetail.map(pdpList => {
                            return (
                                <div key={pdpList.uniqueID} className="col-md-4">
                                    <h2 key={pdpList.uniqueID}/>

                                    <img src={picUrl + pdpList.thumbnail}/>
                                    <p>
                                        Price : {pdpList.price[0].value}{" "}
                                        {pdpList.price[0].currency}
                                    </p>
                                    <button  onClick={() => this.props.addToCart(item)}>Add to Cart</button>
                                </div>
                            );
                        })}
                    </div>
                </div>
            </div>
        );
    }
}

const mapStateToProps = state => {
    return {
        productDetail: state.fashion.productDetail,
        cartDetail: state.fashion.cartDetail
    }
};

const mapActionsToProps = dispatch => {
    return bindActionCreators({
        getDetails: getProductDetail
    }, 
    {
        addToCart: item => dispatch(addToCart(item))
    },dispatch);

};


export default connect(mapStateToProps, mapActionsToProps)(PDP)
import React,{Component}来自“React”;
从“react router dom”导入{Route,Link,BrowserRouter};
从“redux”导入{bindActionCreators};
从'react redux'导入{connect};
从“./actions”导入{getProductDetail};
从“../actions/index”导入{addToCart};
类PDP扩展组件{
componentDidUpdate(prevProps){
让currentId=this.props.match.params.id;
让previousId=previprops.match.params.id;
if(currentId!==previousId){
this.props.getDetails(currentId);
}
}
componentDidMount(){
设{id}=this.props.match.params;
this.props.getDetails(id);
}
render(){
const{productDetail}=this.props;
常量picUrl=”https://149.129.128.3:8443";
返回(
{productDetail&&
productDetail.map(pdpList=>{
返回(

价格:{pdpList.Price[0]。值}{”“}
{pdpList.price[0].货币}

this.props.addToCart(项目)}>添加到购物车 ); })} ); } } 常量mapStateToProps=状态=>{ 返回{ productDetail:state.fashion.productDetail, cartDetail:state.fashion.cartDetail } }; const mapActionsToProps=调度=>{ 返回bindActionCreators({ getDetails:getProductDetail }, { addToCart:item=>dispatch(addToCart(item)) },派遣); }; 导出默认连接(MapStateTrops、mapActionsToProps)(PDP)
)

cart.js

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { removeFromCart } from '../actions/index';

class Cart extends Component {
  render() {
    /**
     * this.props.cart is populated through the redux store and mapStateToProps
     * this.props.removeFromCart is added through mapDispatchToProps
     */
    const cartList = this.props.cart.map(( item, index) =>{
      return <div key={index}> 
        <p style={{ color: "#767676"}}>{item.name} - {item.price} $ </p>
        <button className="button" 
                onClick={ () => this.props.removeFromCart(item)} > 
          Remove 
        </button>
      </div>;
    });

    return (
      <div>
        <h1>Cart</h1>
        <div  className="cart">
          {cartList}
        </div>
      </div>
    );
  }
}

function mapStateToProps(state, props) {
    return {
        cart: state.cartDetail
    };
}

function mapDispatchToProps(dispatch) {
    return {
        removeFromCart: pdpList => dispatch(removeFromCart(pdpList))
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(Cart);
import React,{Component}来自'React';
从'react redux'导入{connect};
从“../actions/index”导入{removeFromCart};
类Cart扩展组件{
render(){
/**
*此.props.cart通过redux商店和mapStateToProps填充
*此.props.removeFromCart是通过mapDispatchToProps添加的
*/
const cartList=this.props.cart.map((项目,索引)=>{
返回

{item.name}-{item.price}$

this.props.removeFromCart(项目)}> 去除 ; }); 返回( 运货马车 {cartList} ); } } 函数mapStateToProps(状态、道具){ 返回{ 购物车:state.cartdail }; } 功能图DispatchToprops(调度){ 返回{ removeFromCart:pdpList=>dispatch(removeFromCart(pdpList)) } } 导出默认连接(mapStateToProps、mapDispatchToProps)(购物车);
我唯一的错误是

有人能帮我解决这个问题吗。我不知道我哪里出错了。如果有人能给我提供一些见解,我将不胜感激。谢谢

问题就在这里
这个.props.addToCart(item)}>添加到购物车
因为
项目
未定义的
,您需要将
项目
替换为
pdpList
变量

<button  onClick={() => this.props.addToCart(pdpList)}>Add to Cart</button>
您的购物车道具未定义

您需要在
fashionReducer.js的
INITIAL_状态中定义
cart

const INITIAL_STATE = {navbar: [], products: [], productDetail:[], cartDetail:[], cart: []};
或者您可以在
MapStateTops
中使用cartDetail(已定义)这样做

function mapStateToProps(state, props) {
    return {
        cart: state.fashion.cartDetail // changed
    };
}
这里的问题是
this.props.addToCart(item)}>添加到购物车
,因为
item
未定义的
,您需要用
pdpList
变量替换
item

<button  onClick={() => this.props.addToCart(pdpList)}>Add to Cart</button>
您的购物车道具未定义

您需要在
fashionReducer.js的
INITIAL_状态中定义
cart

const INITIAL_STATE = {navbar: [], products: [], productDetail:[], cartDetail:[], cart: []};
或者您可以在
MapStateTops
中使用cartDetail(已定义)这样做

function mapStateToProps(state, props) {
    return {
        cart: state.fashion.cartDetail // changed
    };
}

您好,我认为主要问题在于您的MapStateTrops

function mapStateToProps(state, props) {
    return {
        cart: state.fashion.cartDetail // instead of state.cart 
    };
}

您所在州没有任何名为cart的属性,这就是原因。

您好,我认为主要问题在于您的MapStateTrops

function mapStateToProps(state, props) {
    return {
        cart: state.fashion.cartDetail // instead of state.cart 
    };
}

您的状态中没有任何名为cart的属性,这就是原因。

您正在将
传递给
this.props.addToCart
,但您从未定义名为
的变量。那么,我现在该怎么办。如果pdpList是您产品列表中的一项,您能给我一点@JoeClayI的指导吗?我想不是通过pdpList。它的工作希望如此。请声明正确的变量名。是的,@Dhiren所说的正是我要说的:)将正确的变量名传递到
this.props.addToCart
-根据代码判断,您的意思是传递
pdpList
。我已经更改,现在它在我的Cart.js文件中显示错误。我已经上传了我的更新代码。请帮助您将
传递给
this.props.addToCart
,但您从未定义名为
的变量。那么,我现在该怎么办。如果pdpList是您产品列表中的一项,您能给我一点@JoeClayI的指导吗?我想不是通过pdpList。它的工作希望如此。请声明正确的变量名。是的,@Dhiren所说的正是我要说的:)将正确的变量名传递到
this.props.addToCart
-根据代码判断,您的意思是传递
pdpList
。我已经更改了,现在它在我的购物车中显示错误。j