【问题标题】:Items not able to add in reactjs shopping cart无法添加到 reactjs 购物车中的项目
【发布时间】:2019-04-02 05:31:46
【问题描述】:

我在 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)

;

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);

我得到的唯一错误是

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

【问题讨论】:

  • 您将item 传递给this.props.addToCart,但您从未定义名为item 的变量。
  • 那么,我现在该怎么办。你能指导我一点@JoeClay
  • 如果 pdpList 是您产品列表中的一项,我认为不是通过 pdpList 传递项目。它的工作希望如此。请声明正确的变量名。
  • 是的,@Dhiren 所说的正是我要说的 :) 将正确的变量名传递给 this.props.addToCart - 从代码来看,您的意思是传递 pdpList。
  • 我已更改,现在它在我的 Cart.js 文件中显示错误。我已经上传了我更新的代码。请帮忙

标签: reactjs redux


【解决方案1】:

问题出在&lt;button onClick={() =&gt; this.props.addToCart(item)}&gt;Add to Cart&lt;/button&gt;,因为item是undefined,你需要将item替换成pdpList变量。

<button  onClick={() => this.props.addToCart(pdpList)}>Add to Cart</button>

根据问题更新进行更新 现在问题出在这一行

const cartList = this.props.cart.map(( item, index) =>{ // this.props.cart is `undefined`

您的购物车道具是undefined

您需要在INITIAL_STATE 的fashionReducer.js 中定义cart

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

或者您可以像这样在mapStateToProps 中使用 cartDetail(已经定义)

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

【讨论】:

  • 我已经改变了你所说的一切。但它仍然显示无法读取未定义的属性“地图”。
  • 您的购物车状态位于时尚减速机。所以使用state.fashion.cart 而不是state.cart。我以为你已经正确地映射了状态。反正
【解决方案2】:

您好,我认为主要问题在于您的 ma​​pStateToProps

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

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

【讨论】:

  • 更改后仍然显示Cannot read property 'map' of undefined
  • @SajjadTabreez 您好,我知道您正在使用 combineReducers,因此您必须通过 state.fashion 访问状态,所以我更新了我的答案。
  • @SajjadTabreez:欢迎您 :) 请检查答案是否正确。 :p
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-01
  • 2020-05-30
相关资源
最近更新 更多