2018-02-28添加到购物车

The data structure is like :

{cart: [
  {listingId: 1, listing:{id: 1, }, quantity: 10},
  {listingId: 2, listing:{id: 2, }, quantity: 20},
···
]

Thus the actions look like :

export const addToCart = listing => ({
  type: 'ADD_TO_CART',
  listing
})

export const addOne = listingId => ({
  type: 'ADD_ONE',
  listingId
})

export const minusOne = listingId => ({
  type: 'MINUS_ONE',
  listingId
})

When you want to increment one of the listing, first find it in the array, then return the whole state.

import { ADD_TO_CART, ADD_ONE, MINUS_ONE } from './actions'

const initialState = {
  cart: []
}

const cart = (state = initialState.cart, action) => {
  switch (action.type) {
    case ADD_TO_CART:
      return Object.assign({}, state,
        {listing: action.listing, listingId: action.listing.id, quantity: 1})
    case ADD_ONE:
      const plus = state.find(d=>d.listingId===action.listingId)
      plus.quantity++
      return Object.assign({}, state, {cart: plus})
    case MINUS_ONE:
      const minus = state.find(d => d.listingId === action.listingId)
      minus.quantity--
      return Object.assign({}, state, {cart: minus})
    default:
      return state
  }
}

export default cart  

There is sth difficulty in writing addToCart method, currently the Main stateless function :

import React from "react"
import { Query } from 'react-apollo'
import { gql } from 'apollo-boost'
import Product from './Product'
import './Main.css'

const GET_DOG = gql`
  query {
    store(id: 4751) {
      title
      listings(search:{offset:0,limit:10,order_by:"id",order_asc:"asc",per_page:10,page:1,include_deleted:true}) {
      id
      price
      quantity
      created_at
      updated_at
      product_id
      blid
      store_id
      web_price
      department_id
      product {
        id
        name
        image_url
        description
        barcode
        }
      }
    }
  }
`

const Main = () => (
  
    {({loading, error, data}) => {
      if (loading) return 
Loading
if (error) return
Error :
return (

菜单

{data.store.listings.map(listing => ( ))}
) }}
) export default Main

The Product method:

import React from 'react'
import './Product.css'

const Product = (props) => (
  
{props.productData.product.name} {props.productData.price}
) export default Product

你可能感兴趣的:(2018-02-28添加到购物车)