我在了解Redux购物车示例中的removeFromCart实现时遇到问题

时间:2019-04-16 15:32:32

标签: reactjs redux

我不确定在哪里以及如何实现功能removeProduct以及如何对其进行定义。.基本思想是在Redux购物车示例中实现removeProductFromCart功能。 https://github.com/reduxjs/redux/tree/master/examples/shopping-cart

到目前为止我尝试过的:

action.js

           const deleteFromCart = productId => ({
                 type: types.REMOVE_PRODUCT,
                 productId
            })

           export const removeProduct = productId => (dispatch)=> {
                  dispatch(deleteFromCart(productId))
            }

cartReducer.js

           const addedIds = (state = initState.addedIds, action) => {
                   switch (action.type) {
                       case ADD_PRODUCT:

                       if(state.indexOf(action.productId) !== - 1){
                             return state
                       }
                       return [ ...state, action.productId ]

                       case REMOVE_PRODUCT:

                           return state.filter(productId => action.productId !== productId)

                       default:
                           return state
                    }
              }

          const quantityById = (state = initState.quantityById, action ) => {
                  switch (action.type) {
                       case ADD_PRODUCT:
                  const { productId } = action
                  return {
                        ...state,
                        [productId]:(state[productId] || 0) + 1
                  }
                       case REMOVE_PRODUCT:
                  return { 
                        ...state,
                        [productId]: state[productId] - 1
                  } 
                     default:
                         return state
                  }
             }

Cart.js

     const Cart = ({products, total, onCheckoutClicked, 
     onDeleteFromCart }) => {

     const hasProducts = products.length > 0

     const nodes = hasProducts ? (

     products.map(product =>

         <div key={product.id}>

            <Product
             titulo={product.titulo}
             price={product.price}
             quantity={product.quantity}
             />
            <button
             onClick={onDeleteFromCart}
             disabled={product.inventory < 0 ? 'disabled' :'' }>
            {product.inventory < 0 ? 'Sin productos' : 'Sacar del carrito'}
             </button>

          </div>
         )
       ):(<p>Agregá productos al carrito</p>)

       return (
            <div>
                <h3>Tu Carrito</h3>
                <div>{nodes}</div>
                <p>Total: &#36;{total}</p>
                <button onClick={onCheckoutClicked} disabled={hasProducts ? '' : 'disabled'}>Checkout</button>
             </div>
                )      
               }

          Cart.propTypes = {
           products:PropTypes.array,
           total:PropTypes.string,
           onCheckoutClicked:PropTypes.func,
           onDeleteFromCart:PropTypes.func
      }

    export default  Cart

CartContainer.js

const CartContainer = ({products, total, checkout, removeProduct}) => (

  <Cart
     products={products}
     total={total}
     onCheckoutClicked={()=>checkout(products)}
     onDeleteFromCart={()=>removeProduct(products.map(product => product.id))}
  />
)

CartContainer.propTypes = {
  products: PropTypes.arrayOf(PropTypes.shape({
    id:PropTypes.number.isRequired,
    titulo: PropTypes.string.isRequired,
    price: PropTypes.number.isRequired,
    quantity: PropTypes.number.isRequired
  })).isRequired,
  total:PropTypes.string,
  checkout:PropTypes.func.isRequired,
  removeProduct:PropTypes.func.isRequired
}

const mapStateToProps = (state) => ({
  products: getCartProducts(state),
  total: getTotal(state)
})

export default connect(
  mapStateToProps,
  { checkout, removeProduct }
)(CartContainer)

当我调度动作REMOVE_PRODUCT时,此代码返回一个数组... 所以我不会不明白我如何使它工作..代码不会引发错误,但是我如何才能仅重新运行产品的ID?而不是array..its正确实现CartContainer和cart中的功能? ...对我来说很有意义...但是我看到了一些代码在productitems.js中存在隐含

预先感谢

2 个答案:

答案 0 :(得分:1)

您可能需要修复几件事。

首先,您的action.js有点多余。您应该就能拥有:

export const removeProduct = productId => ({
             type: types.REMOVE_PRODUCT,
             productId
        })

接下来,在您的化简器中,您将要确保扩展状态,然后过滤指定的数组。我假设您的reducer的初始状态如下所示:

const INITIAL_STATE = {
  products: [] <--- An array of products in the cart
}

如果正确,那么减速器中的case应该类似于:

case REMOVE_FROM_OBJECT_ARRAY:
        return {
            ...state,
            products: state.products.filter(product => product.id !== action.productId),
        };

此后,当您需要将removeProduct操作传递给<Cart/>组件时,应该是:

onDeleteFromCart={this.props.removeProduct}

由于您要将该动作分配给道具。

最后,您需要将产品ID传递到触发操作的按钮的onClick方法中:

onClick={onDeleteFromCart(product.id)}

我希望这能使您朝正确的方向前进。

修改

尝试转换为课程:

class CartContainer extends React.Component {
    constructor(props) {
      super(props);
    }
   // You may not need the constructor
}

handleRemoveProduct = (e, id) => {
  e.preventDefault()
  this.props.removeProduct(id)
}

render() {
  return(
    <Cart
      products={products}
      total={total}
      onCheckoutClicked={()=>checkout(products)}
      onDeleteFromCart={()=>removeProduct(products.map(product => 
      product.id))}
    />
  )
}

CartContainer.propTypes = {
  products: PropTypes.arrayOf(PropTypes.shape({
    id:PropTypes.number.isRequired,
    titulo: PropTypes.string.isRequired,
    price: PropTypes.number.isRequired,
    quantity: PropTypes.number.isRequired
  })).isRequired,
  total:PropTypes.string,
  checkout:PropTypes.func.isRequired,
  removeProduct:PropTypes.func.isRequired
}

const mapStateToProps = (state) => ({
  products: getCartProducts(state),
  total: getTotal(state)
})

export default connect(
  mapStateToProps,
  { checkout, removeProduct }
  )(CartContainer)

然后通过以下方法将此函数传递到您的<Cart/>组件中:

onDeleteFromCart={this.handleRemoveProduct}

然后单击您的按钮:

onClick={(e) => onDeleteFromCart(e, id)}

希望对您有用。

答案 1 :(得分:0)

我无法发表评论,对此表示抱歉。我稍后会删除它。我不明白您到底想做什么。您要从数组中删除ID还是返回ID?