@@ -2,6 +2,8 @@ import { ConfigProvider } from 'antd'
22import Meals from './components/meals'
33import Search from './components/search'
44import Cart from './components/cart'
5+ import cartContext from './store/cart'
6+ import { useState } from 'react'
57
68// 模拟一组食物数据
79const MEALS_DATA = [
@@ -53,14 +55,48 @@ const MEALS_DATA = [
5355]
5456
5557function App ( ) {
58+ const [ mealsData ] = useState ( MEALS_DATA )
59+ const [ cartData , setCartData ] = useState ( {
60+ items : [ ] ,
61+ totalPrice : 0 ,
62+ amount : 0
63+ } )
64+ 65+ const addItem = ( item ) => {
66+ let newMeal = { ...cartData }
67+ newMeal . amount ++
68+ newMeal . totalPrice += item ?. price
69+ if ( newMeal . items . indexOf ( item ) === - 1 ) {
70+ newMeal . items . push ( item )
71+ item . count = 1
72+ 73+ } else {
74+ item . count ++
75+ }
76+ setCartData ( newMeal )
77+ }
78+ 79+ const removeItem = ( item ) => {
80+ let newMeal = { ...cartData }
81+ newMeal . totalPrice -= item ?. price
82+ newMeal . amount --
83+ item . count --
84+ if ( item . count === 0 ) {
85+ newMeal . items . splice ( newMeal . items . indexOf ( item ) , 1 )
86+ }
87+ setCartData ( newMeal )
88+ }
89+ 5690 return (
57- < ConfigProvider theme = { { token : { colorPrimary : '#ffcd00' } } } >
58- < div style = { { width : '750rem' , height : '100vh' , overflow : 'hidden' , position : 'relative' } } >
59- < Search > </ Search >
60- < Meals meals = { MEALS_DATA } > </ Meals >
61- < Cart > </ Cart >
62- </ div >
63- </ ConfigProvider >
91+ < cartContext . Provider value = { { ...cartData , addItem, removeItem } } >
92+ < ConfigProvider theme = { { token : { colorPrimary : '#ffcd00' } } } >
93+ < div style = { { width : '750rem' , height : '100vh' , overflow : 'hidden' , position : 'relative' } } >
94+ < Search > </ Search >
95+ < Meals meals = { mealsData } > </ Meals >
96+ < Cart > </ Cart >
97+ </ div >
98+ </ ConfigProvider >
99+ </ cartContext . Provider >
64100 )
65101}
66102
0 commit comments