Redux:addToCart 功能只是更新数量,而不是将产品添加到购物车 [英] Redux: addToCart function is only updating quantity and not adding the product to cart

查看:83
本文介绍了Redux:addToCart 功能只是更新数量,而不是将产品添加到购物车的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Redux 的新手,因此很难解决代码中的问题,尤其是因为我没有错误.

每当我将产品添加到购物车时,我的状态都会更新,但它只会更新购物车的数量,而实际上并未将产品添加到购物车.

下面是我的 Redux 工具和相关代码片段的屏幕截图.

Card.js

import React, {useState} from 'react';导入 'antd/dist/antd.css';import { Card, Avatar, Button, Modal } from 'antd';import { EditOutlined, EllipsisOutlined, PlusCircleTwoTone, SettingOutlined } from '@ant-design/icons';从'react-redux'导入{connect};从../Redux/Shopping/ShoppingActions"导入 {addToCart}const { 元 } = 卡;功能卡多(道具){const {addToCart} = 道具;//设置变量用于useState,以便管理模态状态//默认状态为false所以不可见const [isModalVisible, setIsModalVisible] = useState(false);const showModal = () =>{setIsModalVisible(true);};const handleOk = () =>{setIsModalVisible(false);};const handleCancel = () =>{setIsModalVisible(false);};//^^^上面所有的const都会在card或者modal里面调用下面来管理modal的状态返回 (<div className="卡片"><卡片style={{ width: "340px", textAlign: 'center' }}cover={<img className="card-cover";src={props.image}/>}动作={[//<SettingOutlined key="设置";/>,//<EditOutlined onClick={showModal} key=edit";/>,<EllipsisOutlined onClick={showModal} key=省略号";/>,]}><元avatar={

)}const mapDispatchToProps = (调度) =>{返回{addToCart: (id) =>调度(addToCart(id)),}}导出默认连接(null,mapDispatchToProps)(Cardo)

ShoppingReducer.js

import * as actionTypes from './ShoppingTypes';从'../../Data/MenuData'导入数据;const INITIAL_STATE = {产品:数据,//(id,标题,描述,价格,img)购物车: [],//(id, title, description, price, img, qty)当前项目:空,}//reducer 只是接收状态和动作的函数 - 动作是包含类型的分派部分const shopReducer = (state = INITIAL_STATE, action) =>{开关(动作.类型){案例 actionTypes.ADD_TO_CART://从products数组中获取items数据const item = state.products.find((product) => product.id === action.payload.id);//我们需要检查项目是否已经在购物车中const inCart = state.cart.find((item) => item.id === action.payload.id ? true : false);返回{//我们首先传播状态,以免丢失当前或所有产品...状态,//inCart 我们检查它是否在购物车中并返回 true - 如果是,则通过购物车映射并找到该 ID购物车: inCart ?state.cart.map((item) =>item.id === action.payload.id//然后在里面传播所有数据并根据需要更改数量?{...item, qty: item.qty + 1} : item)//如果不在购物车中,则展开数组并将项目和数量添加到购物车状态: [...state.cart, { ...item, qty: 1}],};案例 actionTypes.REMOVE_FROM_CART:返回{...状态,//这会过滤数组并删除我们要删除的项目购物车:state.cart.filter(item => item.id !== action.payload.id)};案例 actionTypes.ADJUST_QTY:返回{...状态,//如果我在购物车中找到 id 我想通过传播当前项目并将数量设置为原始数量来重新创建对象 - 否则返回项目购物车:state.cart.map((item) => item.id === action.payload.id ? {...item, qty: action.payload.qty} : item)};案例 actionTypes.LOAD_CURRENT_ITEM:返回{...状态,当前项目:action.payload,};默认:返回状态;}}导出默认shopReducer;

MenuData.js(保存存储在产品中的数据)

const 数据 = [{编号:1,图片:'https://images.pexels.com/photos/699953/pexels-photo-699953.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940',标题:肉饺子",价格:4.99,//数量:1,描述:'这里有一些描述......'},{编号:2,图片:'https://images.pexels.com/photos/699953/pexels-photo-699953.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940',标题:素食饺子",价格:3.99,//数量:1,描述:'这里有一些描述......'},{编号:3,图片:'https://images.pexels.com/photos/699953/pexels-photo-699953.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940',标题:鸭肉春卷",价格:4.29,//数量:1,描述:'这里有一些描述......'},{编号:4,图片:'https://images.pexels.com/photos/699953/pexels-photo-699953.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940',标题:素食春卷",价格:3.79,//数量:1,描述:'这里有一些描述......'},{编号:5,图片:'https://images.pexels.com/photos/699953/pexels-photo-699953.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940',标题:绿泰咖喱",价格:9.99,//数量:1,描述:'这里有一些描述......'},{编号:6,图片:'https://images.pexels.com/photos/699953/pexels-photo-699953.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940',标题:红泰咖喱",价格:9.99,//数量:1,描述:'这里有一些描述......'},{编号:7,图片:'https://images.pexels.com/photos/699953/pexels-photo-699953.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940',标题:Pad Thai",价格:12.99,//数量:1,描述:'这里有一些描述......'},{编号:8,图片:'https://images.pexels.com/photos/699953/pexels-photo-699953.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940',标题:日本咖喱",价格:10.99,//数量:1,描述:'这里有一些描述......'},{编号:9,图片:'https://images.pexels.com/photos/699953/pexels-photo-699953.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940',标题:麻辣四川豆腐面",价格:8.99,//数量:1,描述:'这里有一些描述......'},{编号:10,图片:'https://images.pexels.com/photos/699953/pexels-photo-699953.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940',标题:豚骨拉面",价格:12.99,//数量:1,描述:'这里有一些描述......'},{编号:11,图片:'https://images.pexels.com/photos/699953/pexels-photo-699953.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940',标题:香辣味噌面",价格:7.99,//数量:1,描述:'这里有一些描述......'},{编号:12,图片:'https://images.pexels.com/photos/699953/pexels-photo-699953.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940',标题:Oyaka Don",价格:8.99,//数量:1,描述:'这里有一些描述......'},{编号:13,图片:'https://images.pexels.com/photos/699953/pexels-photo-699953.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940',标题:抹茶布朗尼",价格:4.99,//数量:1,描述:'这里有一些描述......'},{编号:14,图片:'https://images.pexels.com/photos/699953/pexels-photo-699953.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940',标题:咸焦糖布朗尼",价格:3.99,//数量:1,描述:'这里有一些描述......'},{编号:15,图片:'https://images.pexels.com/photos/699953/pexels-photo-699953.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940',标题:茉莉香米",价格:2.99,//数量:1,描述:'这里有一些描述......'},{编号:16,图片:'https://images.pexels.com/photos/699953/pexels-photo-699953.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940',标题:日本糯米",价格:3.99,//数量:1,描述:'这里有一些描述......'},{编号:17,图片:'https://images.pexels.com/photos/699953/pexels-photo-699953.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940',标题:巴斯马蒂大米",价格:1.99,//数量:1,描述:'这里有一些描述......'},{编号:18,图片:'https://images.pexels.com/photos/699953/pexels-photo-699953.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940',标题:鸡蛋炒饭",价格:3.99,//数量:1,描述:'这里有一些描述......'},]导出默认数据;

MyMenu.js(卡片被映射的地方)

import { Col, Row } from 'antd';从反应"导入反应从 './Card' 导入 Cardo;从'../Data/MenuData'导入数据;从'react-redux'导入{连接};从'../Redux/Shopping/ShoppingReducer'导入shopReducer;从 './ReduxRenderedCard' 导入 ReduxCardo;const cardCreator = (产品) =>{返回(<卡多键={product.id}图像={产品.图像}标头={product.header}价格={产品.价格}描述={产品.描述}/>)}功能 MyMenu({ 产品 }) {返回 (<div className=菜单"><h1 className="menu-header";>初学者</h1><行类名=菜单行"gutter={{xs: 32, sm: 24, md: 16, lg: 8}}>{/* <Col span={{xs: 24, sm: 12, md: 8, lg: 6}}>{products.map(cardCreator1)};</Col>*/}<Col span={{xs: 24, sm: 12, md: 8, lg: 6}}>{products.map(cardCreator)[0]}</Col><Col span={{xs: 24, sm: 12, md: 8, lg: 6}}>{products.map(cardCreator)[1]}</Col><Col span={{xs: 24, sm: 12, md: 8, lg: 6}}>{products.map(cardCreator)[2]}</Col><Col span={{xs: 24, sm: 12, md: 8, lg: 6}}>{products.map(cardCreator)[3]}</Col></行><h1 className="menu-header">Mains</h1><行类名=菜单行"gutter={{xs: 32, sm: 24, md: 16, lg: 8}}><Col span={{xs: 24, sm: 12, md: 8, lg: 6}}>{products.map(cardCreator)[4]}</Col><Col span={{xs: 24, sm: 12, md: 8, lg: 6}}>{products.map(cardCreator)[5]}</Col><Col span={{xs: 24, sm: 12, md: 8, lg: 6}}>{products.map(cardCreator)[6]}</Col><Col span={{xs: 24, sm: 12, md: 8, lg: 6}}>{products.map(cardCreator)[7]}</Col><Col span={{xs: 24, sm: 12, md: 8, lg: 6}}>{products.map(cardCreator)[8]}</Col><Col span={{xs: 24, sm: 12, md: 8, lg: 6}}>{products.map(cardCreator)[9]}</Col><Col span={{xs: 24, sm: 12, md: 8, lg: 6}}>{products.map(cardCreator)[10]}</Col><Col span={{xs: 24, sm: 12, md: 8, lg: 6}}>{products.map(cardCreator)[11]}</Col></行><h1 className="menu-header">Rice</h1><行类名=菜单行"gutter={{xs: 32, sm: 24, md: 16, lg: 8}}><Col span={{xs: 24, sm: 12, md: 8, lg: 6}}>{products.map(cardCreator)[14]}</Col><Col span={{xs: 24, sm: 12, md: 8, lg: 6}}>{products.map(cardCreator)[15]}</Col><Col span={{xs: 24, sm: 12, md: 8, lg: 6}}>{products.map(cardCreator)[16]}</Col><Col span={{xs: 24, sm: 12, md: 8, lg: 6}}>{products.map(cardCreator)[17]}</Col></行><h1 className="menu-header">甜点</h1><行类名=菜单行"gutter={{xs: 24, sm: 12, md: 8, lg: 6}}><Col span={{xs: 24, sm: 12, md: 8, lg: 6}}>{products.map(cardCreator)[12]}</Col><Col span={{xs: 24, sm: 12, md: 8, lg: 6}}>{products.map(cardCreator)[13]}</Col></行>

)}const mapStateToProps = (状态) =>{返回{产品:state.shop.products,};}导出默认连接(mapStateToProps)(MyMenu);

ShoppingActions.js

import * as actionTypes from './ShoppingTypes';export const addToCart = (itemID) =>{返回{类型:actionTypes.ADD_TO_CART,有效载荷:{id:项目ID},};};export const removeFromCart = (itemID) =>{返回{类型:actionTypes.REMOVE_FROM_CART,有效载荷:{id:项目ID},};};export const adjutQty = (itemID, value) =>{返回{类型:actionTypes.ADJUST_QTY,有效载荷:{id:项目ID,数量:价值,},};};export const loadCurrentItem = (item) =>{返回{类型:actionTypes.LOAD_CURRENT_ITEM,有效载荷:项目,};};

解决方案

好像你在某些地方用错了一些 es6 函数,你的代码也有一些错误.

state.cart.find((item) => item.id === action.payload.id ? true : false);

这一行将返回一个 Cart 对象而不是布尔变量,无论如何它可以在您的情况下工作.

主要问题可能来自同一范围内的相同变量名.尝试将地图循环变量名称更改为如下所示的不同.

 返回{//我们首先传播状态,以免丢失当前或所有产品...状态,//inCart 我们检查它是否在购物车中并返回 true - 如果是,则通过购物车映射并找到该 ID购物车: inCart ?state.cart.map((it) =>it.id === action.payload.id//然后在里面传播所有数据并根据需要更改数量?{...item, qty: item.qty + 1} : item)//如果不在购物车中,则展开数组并将项目和数量添加到购物车状态: [...state.cart, { ...item, qty: 1}],};

不确定,这是正确的答案,希望这个答案对您有所帮助.

I am new to Redux so finding it hard to troubleshoot where the issues are in my code especially since I have no errors.

Whenever I add a product to the cart my state is updated however it only updates the quantity of the cart and does not actually add the product to the cart.

Below is a screenshot of my Redux Tools and the relevant code snippets.

Card.js

import React, {useState} from 'react';


import 'antd/dist/antd.css';
import { Card, Avatar, Button, Modal } from 'antd';
import { EditOutlined, EllipsisOutlined, PlusCircleTwoTone, SettingOutlined } from '@ant-design/icons';
import {connect} from 'react-redux';
import {addToCart}  from '../Redux/Shopping/ShoppingActions'



const { Meta } = Card;



function Cardo(props) {
    const {addToCart} = props;


    //Setting variables up to use for useState so to manage state of modal
    //Default state is false so not to be visible
    const [isModalVisible, setIsModalVisible] = useState(false);

    const showModal = () => {
        setIsModalVisible(true);
    };

    const handleOk = () => {
        setIsModalVisible(false);
    };

    const handleCancel = () => {
        setIsModalVisible(false);
    };

    //^^^All the const's above will be called below within the card or modal to manage the state of the modal



    return (
        <div className="card">
            <Card
                style={{ width: "340px", textAlign: 'center' }}
                cover={<img className="card-cover" src={props.image}/>}
                actions={[
                    // <SettingOutlined key="setting" />,
                    // <EditOutlined onClick={showModal} key="edit" />,
                    <EllipsisOutlined onClick={showModal} key="ellipsis" />,
                ]}
            >
                <Meta
                    avatar={<Button className="card-button" onClick={() => addToCart(props.id)} type="primary" shape="circle"><PlusCircleTwoTone /></Button>}
                    title={props.header}
                    description={props.price}
                />
            </Card>
            <Modal title={props.header} visible={isModalVisible} onOk={handleOk} onCancel={handleCancel}>
                <p>{props.description}</p>
            </Modal>
        </div>
    )
}

const mapDispatchToProps = (dispatch) => {
    return{
        addToCart: (id) => dispatch(addToCart(id)),
    }
}

export default connect(null, mapDispatchToProps)(Cardo)

ShoppingReducer.js

import * as actionTypes from './ShoppingTypes';
import data from '../../Data/MenuData';

const INITIAL_STATE = {
    products: data,//(id, title, description, price, img)
    cart: [], //(id, title, description, price, img, qty)
    currentItem: null,
}

//reducer is just function that takes in state and action - action is part that gets dispatched which contains a type
const shopReducer = (state = INITIAL_STATE, action) => {
    switch(action.type){
        case actionTypes.ADD_TO_CART:
            //get items data from products array
            const item = state.products.find((product) => product.id === action.payload.id);
            //we need to check if item is in cart already
            const inCart = state.cart.find((item) => item.id === action.payload.id ? true : false);
            return{
                //we spread the state first so not to lose current or all the products
                ...state,
                //inCart we check if it is in cart and that return true - if so map through cart and find that id
                cart: inCart ? state.cart.map((item) =>
                     item.id === action.payload.id 
                     //Then spread all of data inside and change quantity if needed
                        ? {...item, qty: item.qty + 1} : item
                        ) //if not in cart then spread the array and add the item and quantity to state of cart 
                        : [...state.cart, { ...item, qty: 1}],
            };
        case actionTypes.REMOVE_FROM_CART:
            return{
                ...state,
                //this filters through array and deletes item we want to remove
                cart: state.cart.filter(item => item.id !== action.payload.id)
            };
        case actionTypes.ADJUST_QTY:
            return{
                ...state,
                //if i find id in cart I want to recreate object by spreading current item and setting qty set to original qty - else return item
                cart: state.cart.map((item) => item.id === action.payload.id ? {...item, qty: action.payload.qty} : item)
            };
        case actionTypes.LOAD_CURRENT_ITEM:
            return{
                ...state,
                currentItem: action.payload,
            };
        default:
            return state;
    }

}

export default shopReducer;

MenuData.js (which holds the data that is stored in products)

const data = [

    {
        id: 1,
        image: 'https://images.pexels.com/photos/699953/pexels-photo-699953.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940',
        header: "Meat Dumplings",
        price: 4.99,
        // amount: 1,
        description: 'Some Description here....'
    },
    {
        id: 2,
        image: 'https://images.pexels.com/photos/699953/pexels-photo-699953.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940',
        header: "Veggie Dumplings",
        price: 3.99,
        // amount: 1,
        description: 'Some Description here....'
    },
    {
        id: 3,
        image: 'https://images.pexels.com/photos/699953/pexels-photo-699953.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940',
        header: "Duck Spring Rolls",
        price: 4.29,
        // amount: 1,
        description: 'Some Description here....'
    },
    {
        id: 4,
        image: 'https://images.pexels.com/photos/699953/pexels-photo-699953.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940',
        header: "Veggie Spring Rolls",
        price: 3.79,
        // amount: 1,
        description: 'Some Description here....'
    },
    {
        id: 5,
        image: 'https://images.pexels.com/photos/699953/pexels-photo-699953.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940',
        header: "Green Thai Curry",
        price: 9.99,
        // amount: 1,
        description: 'Some Description here....'
    },
    {
        id: 6,
        image: 'https://images.pexels.com/photos/699953/pexels-photo-699953.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940',
        header: "Red Thai Curry",
        price: 9.99,
        // amount: 1,
        description: 'Some Description here....'
    },
    {
        id: 7,
        image: 'https://images.pexels.com/photos/699953/pexels-photo-699953.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940',
        header: "Pad Thai",
        price: 12.99,
        // amount: 1,
        description: 'Some Description here....'
    },
    {
        id: 8,
        image: 'https://images.pexels.com/photos/699953/pexels-photo-699953.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940',
        header: "Japanese Curry",
        price: 10.99,
        // amount: 1,
        description: 'Some Description here....'
    },
    {
        id: 9,
        image: 'https://images.pexels.com/photos/699953/pexels-photo-699953.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940',
        header: "Spicy Sichuan Tofu Noodles",
        price: 8.99,
        // amount: 1,
        description: 'Some Description here....'
    },
    {
        id: 10,
        image: 'https://images.pexels.com/photos/699953/pexels-photo-699953.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940',
        header: "Tonkotsu Ramen",
        price: 12.99,
        // amount: 1,
        description: 'Some Description here....'
    },
    {
        id: 11,
        image: 'https://images.pexels.com/photos/699953/pexels-photo-699953.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940',
        header: "Spicy Miso Noodles",
        price: 7.99,
        // amount: 1,
        description: 'Some Description here....'
    },
    {
        id: 12,
        image: 'https://images.pexels.com/photos/699953/pexels-photo-699953.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940',
        header: "Oyaka Don",
        price: 8.99,
        // amount: 1,
        description: 'Some Description here....'
    },
    {
        id: 13,
        image: 'https://images.pexels.com/photos/699953/pexels-photo-699953.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940',
        header: "Matcha Brownies",
        price: 4.99,
        // amount: 1,
        description: 'Some Description here....'
    },
    {
        id: 14,
        image: 'https://images.pexels.com/photos/699953/pexels-photo-699953.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940',
        header: "Salted Caramel Brownies",
        price: 3.99,
        // amount: 1,
        description: 'Some Description here....'
    },
    {
        id: 15,
        image: 'https://images.pexels.com/photos/699953/pexels-photo-699953.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940',
        header: "Jasmine Rice",
        price: 2.99,
        // amount: 1,
        description: 'Some Description here....'
    },
    {
        id: 16,
        image: 'https://images.pexels.com/photos/699953/pexels-photo-699953.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940',
        header: "Sticky Japanese Rice",
        price: 3.99,
        // amount: 1,
        description: 'Some Description here....'
    },
    {
        id: 17,
        image: 'https://images.pexels.com/photos/699953/pexels-photo-699953.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940',
        header: "Basmati Rice",
        price: 1.99,
        // amount: 1,
        description: 'Some Description here....'
    },
    {
        id: 18,
        image: 'https://images.pexels.com/photos/699953/pexels-photo-699953.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940',
        header: "Egg Fried Rice",
        price: 3.99,
        // amount: 1,
        description: 'Some Description here....' 
    },
]

export default data;

MyMenu.js (where the card is mapped)

import { Col, Row } from 'antd';
import React from 'react'
import Cardo from './Card';
import data from '../Data/MenuData';
import { connect } from 'react-redux';
import shopReducer from '../Redux/Shopping/ShoppingReducer';
import ReduxCardo from './ReduxRenderedCard';


const cardCreator = (product) => {
    return(
        <Cardo
            key={product.id}
            image={product.image}
            header={product.header}
            price={product.price}
            description={product.description}

        />
    )
}



function MyMenu({ products }) {
    return (
        <div className="menu">
            <h1 className="menu-header" >Starters</h1>
            <Row className="menu-row" gutter={{xs: 32, sm: 24, md: 16, lg: 8}}>
                {/* <Col span={{xs: 24, sm: 12, md: 8, lg: 6}}>
                    {products.map(cardCreator1)};
                </Col> */}
                <Col span={{xs: 24, sm: 12, md: 8, lg: 6}}>
                    {products.map(cardCreator)[0]}   
                </Col>
                <Col span={{xs: 24, sm: 12, md: 8, lg: 6}}>
                    {products.map(cardCreator)[1]}   
                </Col>
                <Col span={{xs: 24, sm: 12, md: 8, lg: 6}}>
                    {products.map(cardCreator)[2]}   
                </Col>
                <Col span={{xs: 24, sm: 12, md: 8, lg: 6}}>
                    {products.map(cardCreator)[3]}   
                </Col>
            </Row>
            <h1 className="menu-header">Mains</h1>
            <Row className="menu-row" gutter={{xs: 32, sm: 24, md: 16, lg: 8}}>
                <Col span={{xs: 24, sm: 12, md: 8, lg: 6}}>
                    {products.map(cardCreator)[4]}   
                </Col>
                <Col span={{xs: 24, sm: 12, md: 8, lg: 6}}>
                    {products.map(cardCreator)[5]}   
                </Col>
                <Col span={{xs: 24, sm: 12, md: 8, lg: 6}}>
                    {products.map(cardCreator)[6]}   
                </Col>
                <Col span={{xs: 24, sm: 12, md: 8, lg: 6}}>
                    {products.map(cardCreator)[7]}   
                </Col>
                <Col span={{xs: 24, sm: 12, md: 8, lg: 6}}>
                    {products.map(cardCreator)[8]}   
                </Col>
                <Col span={{xs: 24, sm: 12, md: 8, lg: 6}}>
                    {products.map(cardCreator)[9]}   
                </Col>
                <Col span={{xs: 24, sm: 12, md: 8, lg: 6}}>
                    {products.map(cardCreator)[10]}   
                </Col>
                <Col span={{xs: 24, sm: 12, md: 8, lg: 6}}>
                    {products.map(cardCreator)[11]}   
                </Col>
            </Row>
            <h1 className="menu-header">Rice</h1>
            <Row className="menu-row" gutter={{xs: 32, sm: 24, md: 16, lg: 8}}>
                <Col span={{xs: 24, sm: 12, md: 8, lg: 6}}>
                    {products.map(cardCreator)[14]}   
                </Col>
                <Col span={{xs: 24, sm: 12, md: 8, lg: 6}}>
                    {products.map(cardCreator)[15]}   
                </Col>
                <Col span={{xs: 24, sm: 12, md: 8, lg: 6}}>
                    {products.map(cardCreator)[16]}   
                </Col>
                <Col span={{xs: 24, sm: 12, md: 8, lg: 6}}>
                    {products.map(cardCreator)[17]}   
                </Col>
            </Row>
            <h1 className="menu-header">Desserts</h1>
            <Row className="menu-row" gutter={{xs: 24, sm: 12, md: 8, lg: 6}}>
                <Col span={{xs: 24, sm: 12, md: 8, lg: 6}}>
                    {products.map(cardCreator)[12]}
                </Col>
                <Col span={{xs: 24, sm: 12, md: 8, lg: 6}}>
                    {products.map(cardCreator)[13]}
                </Col>
            </Row>
        </div>
    )
}

const mapStateToProps = (state) => {
    return{
        products: state.shop.products,
    };

}

export default connect(mapStateToProps)(MyMenu);

ShoppingActions.js

import * as actionTypes from './ShoppingTypes';

export const addToCart = (itemID) => {
    return{
        type: actionTypes.ADD_TO_CART,
        payload: {
            id: itemID
        },
    };
};

export const removeFromCart = (itemID) => {
    return{
        type: actionTypes.REMOVE_FROM_CART,
        payload: {
            id: itemID
        },
    };
};

export const adjutQty = (itemID, value) => {
    return{
        type: actionTypes.ADJUST_QTY,
        payload: {
            id: itemID,
            qty: value,
        },
    };
};

export const loadCurrentItem = (item) => {
    return{
        type: actionTypes.LOAD_CURRENT_ITEM,
        payload: item,
    };
};

解决方案

it seems like you've used some es6 functions wrong way in some places, and there are some mistakes on your code.

state.cart.find((item) => item.id === action.payload.id ? true : false);

This line will return a Cart object instead of boolean variable, anyways it could work in your case.

The main problem could from the same variable name in a same scope. Try to chance the map loop variable name to be difference like below.

            return{
                //we spread the state first so not to lose current or all the products
                ...state,
                //inCart we check if it is in cart and that return true - if so map through cart and find that id
                cart: inCart ? state.cart.map((it) =>
                     it.id === action.payload.id 
                     //Then spread all of data inside and change quantity if needed
                        ? {...item, qty: item.qty + 1} : item
                        ) //if not in cart then spread the array and add the item and quantity to state of cart 
                        : [...state.cart, { ...item, qty: 1}],
            };

Not sure, this is right answer, I hope this answer helpful for you.

这篇关于Redux:addToCart 功能只是更新数量,而不是将产品添加到购物车的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆