0

我正在建立一个电子商店,并且我已经堆叠删除了添加到“购物车”组件中的项目!我已经设法使用 React-Redux 添加项目,但无法创建一个函数来删除“购物车”中的“添加项目”。如果有人可以帮助创建该功能以删除每个项目或清空产品中的整个购物车,我将不胜感激:我的购物车组件代码如下:

import React, { Component } from "react"
import { Card, CardBody, CardHeader, CardTitle, Row, Col } from "reactstrap"
import PanelHeader from "components/PanelHeader/PanelHeader.js"
import { connect } from "react-redux";



class Cart extends Component {
  render () {
    const cart = this.props.cart
    return (
      <>
        <PanelHeader size="sm" />
        <div className="content">
          <Row>
            <Col xs={12}>
              <Card>
                <CardHeader>
                  <CardTitle tag="h4">Products List</CardTitle>
                </CardHeader>
                <CardBody>
                <table class="table table-striped table-hover">
                  <thead>
                    <tr>
                      <th scope="col"><strong>#</strong></th>
                      <th scope="col"><strong>Name</strong></th>
                      <th scope="col"><strong>Code Item</strong></th>
                      <th scope="col"><strong>Quantity</strong></th>
                      <th scope="col"><strong>Price Total</strong></th>
                    </tr>
                  </thead>
                    <tbody>
                      {cart.length > 0 && cart.map((cart, index) => (             
                      <tr key={cart.id}>
                    <th scope="row">{index}</th>
                    <td>{cart.title}</td>
                    <td>{cart.code}</td>
                    <td>{cart.quantity}</td>
                    <td>{cart.price}</td>
                      </tr>))}
                      <td><button onClick ={() => removeItemFromCart()} className="btn btn-danger cart-button px-4">Remove</button></td>
                    </tbody>
                </table>
              </CardBody>
            </Card>
          </Col>
        </Row>
      </div>
    </>
    )
  }
}


const mapStateToProps = (state)=> {
  return {
      cart: state.cart
       }
  }

const mapDispatchToProps = (dispatch) => { 
      return {
        addCart: (product) => {dispatch(addCart(product))}
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(Cart);

先感谢您!PS 我是否需要 mapStateToPros 和 mapDispatchToProps 才能使代码正常工作?我试图将它转换为一个简单的购物车组件并返回一个错误。是不是因为是 Redux 语法造成的?

4

1 回答 1

0

我的减速器文件如下:

import { ADD_TO_CART } from './constants'
import { REMOVE_FROM_CART } from './constants'



const initialState = {
    cart: [],
  }
const ShoppinReducer = (state = initialState, action) => {
  
  switch (action.type) {
    
    case ADD_TO_CART:
      const newCart = [...state.cart]
      
  newCart.push(action.payload)
    return {
        ...state,
        cart: newCart
    }
    case REMOVE_FROM_CART:
    return {
        ...state,
        cart: []
    }
    default:
    return state
  }
}
  export default ShoppinReducer
于 2021-10-26T09:38:27.833 回答