上集精彩
回顾上集:
- 好了,俺要开始学习React了 (基础一) - 掘金 (juejin.cn);
- 好了,俺要开始学习React了(基础二) - 掘金 (juejin.cn);
- 好啦,俺要开始学React啦(基础三)真是一场酣畅淋漓的写作时刻 - 掘金 (juejin.cn);
- React,你是对Redux情有独钟,还是对Zustand非你不嫁? - 掘金 (juejin.cn);
上集俺讲到了Zustand的使用。
本集继续
😁😁😁,老铁们,俺又来继续唠叨了,别嫌俺烦哈,俺尽量少烦点

美团案例
静态页面不想一步步来的话,可以下载源码:链接:pan.baidu.com/s/1v7ZRxHBb...;
- 下载其他的所需依赖:有不知道的可上网查
cmd
npm i axios json-server lodash zustand
- 添加虚拟服务指令:
json
"scripts": {
"serve": "json-server --watch server/data.json --port 3001"
},
展示商品列表
- 状态管理 zustand
cmd
npm install immer


在App.js中引入并log下,看看效果:能行😎(下图商品列表是死数据)

- 启动服务:
cmd
npm run serve

- 展示列表:将 foodsList替换为 categories


左侧菜单
- 菜单组件 Menu ,由于右侧已经获得到了列表数据,就不用再菜单组件 Menu 中再获取重新获取一次了,会给后台服务造成负担的,可以通过父传子组件通信来传递给菜单组件 Menu 值:



- 状态管理菜单激活值activeIndex,并定义一个点击菜单项时该值会发生变化的动作:

- 在Menu组件中添加下图两段代码:

点击各个菜单项后,控制台会输出相应的index值,并且同步持久化。
- 动态更新菜单项类名样式:判断activeIndex是否等于当前的index:
js
// Menu/index.js
className={classNames(
"list-menu-item",
activeIndex === index && "active"
)}

- 将持久化存储修改下,只存储菜单激活
activeIndex
:
js
// store/modules/categorySlice.js
{
name: "categorySlice",
partialize: (state) => ({ activeIndex: state.activeIndex }),
storage: createJSONStorage(() => sessionStorage)
}
- 菜单项对应的商品列表切换显示:如果activeIndex === index && 商品列表视图:


添加购物车实现
- 点击 + 号添加当前商品到购物车列表中,需要对购物车列表进行状态管理:

- 在FoodItem组件中的加号添加点击事件:


购物车数量和总价显示


- 计算总价price*count:


- 购物车高亮显示:


- 结算起送判断:


购物车列表实现
- 购物车列表渲染:直接把cart改为carts就行了,再添加个类名visible


- 修改carts里的count:添加增和减的操作,还有清空的操作



- 显示和隐藏购物车:点击购物车显示购物车列表,点击遮罩层隐藏购物车列表
js
// Cart/index.js
// 控制购物车显示与隐藏
const [visible, setVisible] = useState(false);
{/* 遮罩层 添加visible类名可以显示出来 */}
<div
className={classNames("cartOverlay", visible && "visible")}
onClick={() => setVisible(false)}
/>
{/* 购物车数量 */}
<div
onClick={() => setVisible(true)}
className={classNames("icon", carts.length > 0 && "fill")}
>
{/* 添加visible类名 div会显示出来 */}
<div className={classNames("cartPanel", visible && "visible")}>

下集精彩
好了,完事,歇歇了😫

下篇俺会讲到哪些知识点呢: 如有不当的地方,原谅解。只要懂得这篇的知识点就很棒了。
- React Router;
- CSS Module;
