2018-02-28添加到购物车
2018-02-28 本文已影响0人
NOTEBOOK2
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 = () => (
<Query query={GET_DOG}>
{({loading, error, data}) => {
if (loading) return <div>Loading</div>
if (error) return <div>Error :</div>
return (
<div className="App">
<header className="App-header">
<h1 className="App-title">菜单</h1>
</header>
<div className="products">
{data.store.listings.map(listing => (
<Product key={listing.id} productData={listing} />
))}
</div>
</div>
)
}}
</Query>
)
export default Main
The Product method:
import React from 'react'
import './Product.css'
const Product = (props) => (
<div className='product-wrap'>
<div className='product-img-wrap'>
<img src={props.productData.product.image_url} alt="" className='product-img'/>
</div>
<div className='product-info'>
<span className='product-name'>{props.productData.product.name}</span>
<span className='product-price'>{props.productData.price}</span>
</div>
<button className='add-to-cart'>加入购物车</button>
</div>
)
export default Product