簡體   English   中英

無法在React Redux Reducer中從購物車中刪除商品

[英]Cannot remove item from shopping cart in React Redux reducer

所以我在一個電子商務網站上工作,這是購物車。 我可以添加項目,但是刪除不能正常工作。 我的狀態中有cartItems。 我可以向cartItems數組添加項目(每個項目都是具有ID,名稱,價格等的對象)。 每個項目都在模態中顯示,帶有數量和一個刪除按鈕。 當我單擊“刪除”按鈕時,該項目不會消失,而應該消失。 我正在控制台記錄日志以進行調試,並且在減速器中收到了正確的有效負載。 問題是模式沒有將其刪除。 任何建議將不勝感激。

這是我的購物車模式:

import React from 'react';
import { connect } from 'react-redux';
import { withStyles } from '@material-ui/core/styles';
import Typography from '@material-ui/core/Typography';
import Modal from '@material-ui/core/Modal';
import Button from '@material-ui/core/Button';
import SvgIcon from '@material-ui/core/SvgIcon';
import ShoppingCart from '@material-ui/icons/ShoppingCart';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableRow from '@material-ui/core/TableRow';
import { removeFromCart } from '../actions/removeFromCartAction';
import { uniqBy } from 'lodash';

const styles = theme => ({
  paper: {
    position: 'absolute',
    top: '50%',
    left: '25%',
    // width: theme.spacing.unit * 50,
    backgroundColor: theme.palette.background.paper,
    boxShadow: theme.shadows[5],
    padding: theme.spacing.unit * 4,
  },
});

class SimpleModal extends React.Component {

  state={
    open: false,
  }

  handleOpen = () => {
    this.setState({ open: true });
  };

  handleClose = () => {
    this.setState({ open: false });
  };

  getUniqueItems = () => {
    const initailUniqueItemsArray = uniqBy( this.props.cartItems, 'id')
    const uniqueItems = initailUniqueItemsArray.map( ( uniqueItem ) => {
      const quantity = this.props.cartItems.reduce( ( accumulator, cartItem ) => {
        if ( uniqueItem.id === cartItem.id ) {
          accumulator++;
        }
        return accumulator;
      }, 0);
      return {
        id: uniqueItem.id,
        title: uniqueItem.title,
        price: uniqueItem.price,
        quantity
      }
    })
    return uniqueItems
  };

  removeFromCartHandler = (cartItem) => {
    this.props.onRemove(cartItem)
    console.log("RemoveHandler", cartItem)
    //console.log("RemoveHandler",id)
  }

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

    let items;
    if ( this.props.cartItems ) {
      //console.log('compare!',this.getUniqueItems(), this.props.cartItems)
      const finalUniqueItems = this.getUniqueItems();
      items = finalUniqueItems.map( merch => (
        <TableRow key={merch.id} >
          <TableCell>{merch.title}</TableCell>
          <TableCell>{merch.price}</TableCell>
          <TableCell>{merch.quantity}</TableCell>
          <TableCell>
          <Button 
            variant="outlined" 
            className={classes.button} 
            onClick={() => this.removeFromCartHandler(merch)} >
            Remove
          </Button>
          </TableCell>
        </TableRow>
      ))}

    let total;
    if ( this.props.cartItems ) {
      total = (this.props.cartItems).reduce(function (accumulator, item) {
        return accumulator + item.price;
      }, 0);}

    return (

      <div>
        <Button onClick={this.handleOpen}>
          <SvgIcon>
            <ShoppingCart />
          </SvgIcon>
        </Button>
        <Modal
          aria-labelledby="simple-modal-title"
          aria-describedby="simple-modal-description"
          open={this.state.open}
          onClose={this.handleClose}
        >
          <div className={classes.paper}>
            <Typography variant="h6" id="modal-title">
              My Cart
            </Typography>
            <Table>
              <TableBody>
                {items}
                <TableRow >
                  <TableCell>Total</TableCell>
                  <TableCell>{total}</TableCell>
                </TableRow>
            </TableBody>
            </Table>
            <SimpleModalWrapped />
          </div>
        </Modal>
      </div>
    )
  }
}

const mapStateToProps = state => {
  console.log("$&",state.card.id)
  // console.log("----->",state.data.cardData)
  if (!state.data.cardData) {
    return {
      title: null,
      id: null,
      img: null,
      description: null,
      price: null
    }
  }

  const card = state.data.cardData[state.card.id]
  return {
    card: card,
    cartItems: state.shoppingCart.cartItems,
    id: state.card.id,

  };
}
const mapDispatchToProps = (dispatch) => {
  return{
    onRemove: (merch) => dispatch(removeFromCart(merch)) 
  }
}

const SimpleModalWrapped = withStyles(styles)(SimpleModal);

export default connect(mapStateToProps, mapDispatchToProps)(withStyles(styles)(SimpleModalWrapped));

這是我的動作:

import { ADD_TO_CART } from './types';

export const addToCart = (card) => dispatch => {
  console.log('TOTAL', card);
  dispatch({
    type: ADD_TO_CART,
    payload: card
  }) 
}

export const test = {
  addToCart: (card) => {
    console.log('TOTAL', card);
    return {
      type: ADD_TO_CART,
      payload: card
    } 
  }
}

這是我的減速器:

import {ADD_TO_CART} from '../actions/types';
import {REMOVE_FROM_CART} from '../actions/types';

const initialState = {
  cards: [],
  id: '',
  cartItems: [],
}

export default function(state = initialState, action) {
  switch(action.type) {
    case ADD_TO_CART:
    console.log('ADD_reducer');
      return {
        ...state,
        cartItems: [...state.cartItems, action.payload],
      }
    case REMOVE_FROM_CART:
    console.log('REMOVE_REDUCER', action.payload, state.cartItems);
    // const newCartItems = state.cartItems.filter( item => item !== state.cartItems[action.index] )
      return {
        ...state,
        // cartItems: newCartItems
        cartItems: state.cartItems.filter(item => item !== action.payload)

        // cartItems: state.cartItems.filter(cartItem => action.payload !== cartItem)
        // cartItems: [...state.cartItems.splice( action.payload )]
      }
    default:
      return state;
  }
}

而不是比較數組,您必須在過濾時比較其ID

case REMOVE_FROM_CART:
    console.log('REMOVE_REDUCER', action.payload, state.cartItems);
      return {
        ...state,
        cartItems: state.cartItems.filter(item => item.id !== action.payload.id)
      }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM