react 之 美团案例

news2024/10/6 2:27:08

1.案例展示

![](https://img-blog.csdnimg.cn/direct/b7a9604e5d274504ad630427a996aa8b.png
在这里插入图片描述

2.环境搭建

  1. 克隆项目到本地(内置了基础静态组件和模版)
git clone http://git.itcast.cn/heimaqianduan/redux-meituan.git 
  1. 安装所有依赖
npm i 
  1. 启动mock服务(内置了json-server)
npm run serve 
  1. 启动前端服务
npm run start 

3.分类和商品列表渲染

在这里插入图片描述
1.store modules 下 takeaway.js文件

// 编写store
import { createSlice } from "@reduxjs/toolkit"
import axios from "axios"

const foodsStore = createSlice({
  name: 'foods',
  initialState: {
    // 商品列表
    foodsList: [],a
  },
  reducers: {
    // 更改商品列表
    setFoodsList (state, action) {
      state.foodsList = action.payload
    }
  }
})

// 异步获取部分
const { setFoodsList} = foodsStore.actions
const fetchFoodsList = () => {
  return async (dispatch) => {
    // 编写异步逻辑
    const res = await axios.get('http://localhost:3004/takeaway')
    // 调用dispatch函数提交action
    dispatch(setFoodsList(res.data))
  }
}

export { fetchFoodsList }

const reducer = foodsStore.reducer
export default reducer

2.store下index.js文件

import foodsReducer from './modules/takeaway'
import { configureStore } from '@reduxjs/toolkit'
const store = configureStore({
  reducer: {
    foods: foodsReducer
  }
})
export default store

3.app.js

import { useDispatch, useSelector } from 'react-redux'
import { fetchFoodsList } from './store/modules/takeaway'
import { useEffect } from 'react'
// 触发action执行
  // 1. useDispatch -> dispatch 2. actionCreater导入进来 3.useEffect
  const dispatch = useDispatch()
  useEffect(() => {
    dispatch(fetchFoodsList())
  }, [dispatch])
  // 获取foodsList渲染数据列表
  // 1. useSelector
  const { foodsList } = useSelector(state => state.foods)
   {/* 外卖商品列表 */}
              {foodsList.map((item, index) => {
                return (
                 <FoodsCategory
                    key={item.tag}
                    // 列表标题
                    name={item.name}
                    // 列表商品
                    foods={item.foods}
                  />
                )
              })}

4.menu.js

import { useDispatch,useSelector } from 'react-redux'
const dispatch = useDispatch()
const {foodsList} = useSelector(state=>state.foods) 

5.index.js

// 注入store
import { Provider } from 'react-redux'
import store from './store'
const root = createRoot(document.getElementById('root'))
root.render(
  <Provider store={store}>
    <App />
  </Provider>
)

4.点击分类激活实现

在这里插入图片描述
1.store modules下 takeaway.js文件


// 编写store
import { createSlice } from "@reduxjs/toolkit"
import axios from "axios"
const foodsStore = createSlice({
  name: 'foods',
  initialState: {
    // 商品列表
    foodsList: [],
    //激活index
    activeIndex:0,
  },
  reducers: {
    // 更改商品列表
    setFoodsList (state, action) {
      state.foodsList = action.payload
    },
    //更改activeIndex
    changeActiveIndex(state,action){
        state.activeIndex = action.payload
    }
  }
})

// 异步获取部分
const { setFoodsList,changeActiveIndex} = foodsStore.actions

2.menu.js

import classNames from 'classnames'
import './index.scss'

import { useDispatch,useSelector } from 'react-redux'
import { changeActiveIndex} from '../../store/modules/takeaway'
const Menu = () => {
  const dispatch = useDispatch()
  const {foodsList,activeIndex} = useSelector(state=>state.foods) 
  const menus = foodsList.map(item => ({ tag: item.tag, name: item.name }))
  return (
    <nav className="list-menu">
      {/* 添加active类名会变成激活状态 */}
      {menus.map((item, index) => {
        return (
          <div
          onClick={() => dispatch(changeActiveIndex(index))}
            key={item.tag}
            className={classNames(
              'list-menu-item',
              activeIndex === index && 'active'
            )}
          >
            {item.name}
          </div>
        )
      })}
    </nav>
  )
}

export default Menu

3.app.js

const { foodsList , activeIndex} = useSelector(state => state.foods)
<div className="goods-list">
              {/* 外卖商品列表 */}
              {foodsList.map((item, index) => {
                return (
                  activeIndex==index && <FoodsCategory
                    key={item.tag}
                    // 列表标题
                    name={item.name}
                    // 列表商品
                    foods={item.foods}
                  />
                )
              })}
            </div>

5.添加购物车

在这里插入图片描述
1.takeaway.js

// 编写store

import { createSlice } from "@reduxjs/toolkit"
import axios from "axios"

const foodsStore = createSlice({
  name: 'foods',
  initialState: {
    // 商品列表
    foodsList: [],
    // 菜单激活下标值
    activeIndex: 0,
    // 购物车列表
    cartList: []
  },
  reducers: {
    // 更改商品列表
    setFoodsList (state, action) {
      state.foodsList = action.payload
    },
    // 更改activeIndex
    changeActiveIndex (state, action) {
      state.activeIndex = action.payload
    },
    // 添加购物车
    addCart (state, action) {
      // 是否添加过?以action.payload.id去cartList中匹配 匹配到了 添加过
      const item = state.cartList.find(item => item.id === action.payload.id)
      if (item) {
        item.count++
      } else {
        state.cartList.push(action.payload)
      }
    },
  }
})

const { setFoodsList, changeActiveIndex, addCart} = foodsStore.actions
export { fetchFoodsList, changeActiveIndex, addCart}

2.foodItem下index.js文件

import { useDispatch } from 'react-redux'
import { setCarlist } from '../../../store/modules/takeaway'
const dispatch = useDispatch()
 <div className="goods-count">
            <span className="plus" onClick={() => dispatch(setCarlist({
              id,
              picture,
              name,
              unit,
              description,
              food_tag_list,
              month_saled,
              like_ratio_desc,
              price,
              tag,
              count
            }))}></span>
          </div>

6.统计区域功能实现

在这里插入图片描述
在这里插入图片描述
1.cart下面index.js

import classNames from 'classnames'
import { useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import Count from '../Count'
import './index.scss'


const Cart = () => {
  const { carList } = useSelector(state => state.foods)
  // 计算总价 
  const totalPrice = carList.reduce((a, c) => a + c.price * c.count, 0)
  return (
    <div className="cartContainer">
      <div className="cart">
        {/* fill 添加fill类名购物车高亮*/}
        {/* 购物车数量 */}
        <div  className={classNames('icon', carList.length > 0 && 'fill')}>
          {carList.length > 0 && <div className="cartCornerMark">{carList.length}</div>}
        </div>
        {/* 购物车价格 */}
        <div className="main">
          <div className="price">
            <span className="payableAmount">
              <span className="payableAmountUnit">¥</span>
              {totalPrice.toFixed(2)}
            </span>
          </div>
          <span className="text">预估另需配送费 ¥5</span>
        </div>
        {/* 结算 or 起送 */}
        {carList.length > 0 ? (
          <div className="goToPreview">去结算</div>
        ) : (
          <div className="minFee">1元起送</div>
        )}
      </div>
      {/* 添加visible类名 div会显示出来 */}
      <div className={classNames('cartPanel')}>
        <div className="header">
          <span className="text">购物车</span>
          <span className="clearCart">
            清空购物车
          </span>
        </div>

        {/* 购物车列表 */}
        <div className="scrollArea">
          {carList.map(item => {
            return (
              <div className="cartItem" key={item.id}>
                <img className="shopPic" src={item.picture} alt="" />
                <div className="main">
                  <div className="skuInfo">
                    <div className="name">{item.name}</div>
                  </div>
                  <div className="payableAmount">
                    <span className="yuan">¥</span>
                    <span className="price">{item.price}</span>
                  </div>
                </div>
                <div className="skuBtnWrapper btnGroup">
                  {/* 数量组件 */}
                  <Count
                    count={item.count}
                 
                  />
                </div>
              </div>
            )
          })}
        </div>
      </div>
    </div>
  )
}

export default Cart


7.购物车列表功能实现

在这里插入图片描述
在这里插入图片描述
1.takeaway.js

// 编写store

import { createSlice } from "@reduxjs/toolkit"
import axios from "axios"

const foodsStore = createSlice({
  name: 'foods',
  initialState: {
    // 商品列表
    foodsList: [],
    //激活index
    activeIndex:0,
    //汽车
    carList:[]
  },
  reducers: {
    // 更改商品列表
    setFoodsList (state, action) {
      state.foodsList = action.payload
    },
    //更改activeIndex
    changeActiveIndex(state,action){
        state.activeIndex = action.payload
    },
    setCarlist(state,action){
      // 是否添加过?以action.payload.id去cartList中匹配 匹配到了 添加过
      const item = state.carList.find(item => item.id === action.payload.id)
      if (item) {
        item.count++
      } else {
        state.carList.push(action.payload)
      }
    },
    increCount(state,action){
      const item = state.carList.find(item => item.id === action.payload.id)
      item.count++
    },
    decreCount(state,action){
        const item = state.carList.find(item => item.id === action.payload.id)
        if(item.count===0){
         return
        }
      item.count--
    },
     // 清除购物车
     clearCart (state) {
        state.carList = []
      }
    
}
})

// 异步获取部分
const { setFoodsList,changeActiveIndex,setCarlist,increCount,decreCount,clearCart} = foodsStore.actions
const fetchFoodsList = () => {
  return async (dispatch) => {
    // 编写异步逻辑
    const res = await axios.get('http://localhost:3004/takeaway')
    // 调用dispatch函数提交action
    dispatch(setFoodsList(res.data))
  }
}

export { fetchFoodsList ,changeActiveIndex,setCarlist,increCount,decreCount,clearCart}

const reducer = foodsStore.reducer

export default reducer

2.cart下index文件

import classNames from 'classnames'
import { useDispatch, useSelector } from 'react-redux'
import Count from '../Count'
import './index.scss'
import {increCount,decreCount,clearCart} from '../../store/modules/takeaway'


const Cart = () => {
  const { carList } = useSelector(state => state.foods)
  // 计算总价 
  const totalPrice = carList.reduce((a, c) => a + c.price * c.count, 0)

  const dispatch = useDispatch()

  return (
    <div className="cartContainer">
      <div className="cart">
        {/* fill 添加fill类名购物车高亮*/}
        {/* 购物车数量 */}
        <div  className={classNames('icon', carList.length > 0 && 'fill')}>
          {carList.length > 0 && <div className="cartCornerMark">{carList.length}</div>}
        </div>
        {/* 购物车价格 */}
        <div className="main">
          <div className="price">
            <span className="payableAmount">
              <span className="payableAmountUnit">¥</span>
              {totalPrice.toFixed(2)}
            </span>
          </div>
          <span className="text">预估另需配送费 ¥5</span>
        </div>
        {/* 结算 or 起送 */}
        {carList.length > 0 ? (
          <div className="goToPreview">去结算</div>
        ) : (
          <div className="minFee">1元起送</div>
        )}
      </div>
      {/* 添加visible类名 div会显示出来 */}
      <div className={classNames('cartPanel',carList.length>0&&'visible')} >
        <div className="header">
          <span className="text">购物车</span>
          <span className="clearCart" onClick={()=>dispatch(clearCart())}>
            清空购物车
          </span>
        </div>

        {/* 购物车列表 */}
        <div className="scrollArea">
          {carList.map(item => {
            return (
              <div className="cartItem" key={item.id}>
                <img className="shopPic" src={item.picture} alt="" />
                <div className="main">
                  <div className="skuInfo">
                    <div className="name">{item.name}</div>
                  </div>
                  <div className="payableAmount">
                    <span className="yuan">¥</span>
                    <span className="price">{item.price}</span>
                  </div>
                </div>
                <div className="skuBtnWrapper btnGroup">
                  {/* 数量组件 */}
                  <Count
                    count={item.count}
                    onPlus={()=>dispatch(increCount({id:item.id}))}
                    onMinus={()=>dispatch(decreCount({id:item.id}))}
                  />
                </div>
              </div>
            )
          })}
        </div>
      </div>
    </div>
  )
}

export default Cart

8.控制购物车显示和隐藏

在这里插入图片描述

在这里插入图片描述
1.cart文件下index.js文件

import classNames from 'classnames'
import { useDispatch, useSelector} from 'react-redux'
import { useState } from 'react'
import Count from '../Count'
import './index.scss'
import {increCount,decreCount,clearCart} from '../../store/modules/takeaway'


const Cart = () => {
  const { carList } = useSelector(state => state.foods)
  // 计算总价 
  const totalPrice = carList.reduce((a, c) => a + c.price * c.count, 0)
  const [visible,setVisible]= useState(false)
  const dispatch = useDispatch()

  const onShow = () => {
    if (carList.length > 0) {
      setVisible(true)
    }
  }
  return (
    <div className="cartContainer">
       {/* 遮罩层 添加visible类名可以显示出来 */}
       <div
        className={classNames('cartOverlay', visible && 'visible')}
        onClick={() => setVisible(false)}
      />
      <div className="cart">
        {/* fill 添加fill类名购物车高亮*/}
        {/* 购物车数量 */}
        <div onClick={onShow}  className={classNames('icon', carList.length > 0 && 'fill')}>
          {carList.length > 0 && <div className="cartCornerMark">{carList.length}</div>}
        </div>
        {/* 购物车价格 */}
        <div className="main">
          <div className="price">
            <span className="payableAmount">
              <span className="payableAmountUnit">¥</span>
              {totalPrice.toFixed(2)}
            </span>
          </div>
          <span className="text">预估另需配送费 ¥5</span>
        </div>
        {/* 结算 or 起送 */}
        {carList.length > 0 ? (
          <div className="goToPreview">去结算</div>
        ) : (
          <div className="minFee">1元起送</div>
        )}
      </div>
      {/* 添加visible类名 div会显示出来 */}
      <div className={classNames('cartPanel',visible &&'visible')} >
        <div className="header">
          <span className="text">购物车</span>
          <span className="clearCart" onClick={()=>dispatch(clearCart())}>
            清空购物车
          </span>
        </div>

        {/* 购物车列表 */}
        <div className="scrollArea">
          {carList.map(item => {
            return (
              <div className="cartItem" key={item.id}>
                <img className="shopPic" src={item.picture} alt="" />
                <div className="main">
                  <div className="skuInfo">
                    <div className="name">{item.name}</div>
                  </div>
                  <div className="payableAmount">
                    <span className="yuan">¥</span>
                    <span className="price">{item.price}</span>
                  </div>
                </div>
                <div className="skuBtnWrapper btnGroup">
                  {/* 数量组件 */}
                  <Count
                    count={item.count}
                    onPlus={()=>dispatch(increCount({id:item.id}))}
                    onMinus={()=>dispatch(decreCount({id:item.id}))}
                  />
                </div>
              </div>
            )
          })}
        </div>
      </div>
    </div>
  )
}

export default Cart

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1342028.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

苹果手机打开Microsoft Outlook日历ics文件方法

作为一名经常需要处理各种日程安排的苹果用户&#xff0c;我深知ics文件的重要性。ics文件通常来自于我们日常使用的日历应用&#xff0c;比如Microsoft Outlook&#xff0c;是日程信息的标准格式。但很多时候&#xff0c;当我们尝试打开这些ics文件时&#xff0c;却会遇到种种…

re:Invent 2023技术上新|Amazon DynamoDB与OpenSearch Service的Zero-ETL集成

Amazon DynamoDB 与 Amazon OpenSearch Service 的 Zero-ETL 集成已正式上线&#xff0c;该服务允许您通过自动复制和转换您的 DynamoDB 数据来搜索数据&#xff0c;而无需自定义代码或基础设施。这种 Zero-ETL 集成减少了运营负担和成本&#xff0c;使您能够专注于应用程序。这…

mysql查询出json格式字段中的值

一、使用场景 由于一些特殊数据使用json格式保存到表数据种中了&#xff0c;在查询的时候需要查询出这条数据中json格式中的某个字段 比如&#xff1a;需要将下列字符串中的“nationality”字段单独查询出来 json格式是一个对象 结果&#xff1a; json格式是一个集合 查询结…

2023量子科技十大进展 | 光子盒年度系列

量子力学是20世纪初成熟的理论&#xff0c;一个多世纪以来一直令科学家们感到惊讶、好奇和困惑。尽管该理论具有反直觉的性质&#xff0c;但它却以优异的成绩通过了实验测试&#xff0c;不断揭示出一个与我们的日常经验相去甚远的世界。 时至今日&#xff0c;科学家们仍然忙于操…

CRM诞生到现在历经了哪些发展阶段?CRM系统的五个关键节点

CRM管理系统从被发明到现在&#xff0c;历经多次迭代已经成为一个相对成熟的系统。企业可以靠它管理客户信息&#xff0c;提升盈利能力。今天就来介绍一下CRM的发展历程。 一、CRM系统的雏形 广义上的CRM系统其实可以追溯到古希腊时期。当时的商人靠书写记录自己与客户和合作…

FileZilla的使用主动模式与被动模式

&#x1f3ac; 艳艳耶✌️&#xff1a;个人主页 &#x1f525; 个人专栏 &#xff1a;《产品经理如何画泳道图&流程图》 ⛺️ 越努力 &#xff0c;越幸运 目录 一、FileZilla简介 1、FileZilla是什么&#xff1f; 2、FileZilla的应用场景 二、FileZilla的安装 1、下…

参数归一化-实现时间格式化

文章目录 需求分析具体实现完整源码 不知道大家有没有尝试封装过一个时间格式化的函数啊&#xff0c;在之前我封装的时候&#xff0c;开始是觉得手到擒来&#xff0c;但是实践之后发现写非常的shi啊&#xff0c;大量的分支判断&#xff0c;哪怕是映射起到的作用也只是稍微好一点…

【小程序】如何获取特定页面的小程序码

一、进入到小程序管理后台&#xff0c;进入后点击上方的“工具”》“生成小程序码” 小程序管理后台 二、进入开发者工具&#xff0c;打开对应的小程序项目&#xff0c;复制底部小程序特定页面的路径 三、粘贴到对应位置的文本框&#xff0c;点击确定即可

NCNN环境部署及yolov5pt转ncnn模型转换推理

该内容还未完整&#xff0c;笔记内容&#xff0c;持续补充。 〇开发环境版本 vs2022 cmake3.21.1 ncnn20231027发行版 yolov5s v6.2 vunlkan1.2.198.1 Protobuf3.20.0 Opencv3.4.1 一、模型转换 yolov5s v6.2训练的pt模型&#xff0c;直接导出tourchscript&#xff0c…

鸿蒙APP的代码规范

鸿蒙APP的代码规范是为了确保代码质量、可读性和可维护性而定义的一系列规则和标准。以下是一些建议的鸿蒙APP代码规范&#xff0c;希望对大家有所帮助。北京木奇移动技术有限公司&#xff0c;专业的软件外包开发公司&#xff0c;欢迎交流合作。 1. 代码风格&#xff1a; 采用…

Wish流量推送规则是什么?wish怎么增加流量?-站斧浏览器

Wish流量推送规则是什么&#xff1f; 个性化推送&#xff1a;Wish采用智能化的算法&#xff0c;根据用户的购物历史、浏览记录、搜索行为等数据&#xff0c;为每位用户推送个性化的商品推荐。这种推送方式能够提高商品与用户的匹配度&#xff0c;从而提高转化率。 价格与销量…

视频转换为GIF格式的3种方法

如果你想与朋友分享一个有趣的瞬间或者在社交媒体上发布一些搞笑的短视频&#xff0c;那么GIF格式将会是一个绝佳的选择。因为相比于视频&#xff0c;GIF文件具有更小的文件大小和更好的兼容性。不过&#xff0c;并不是所有人都知道如何将视频转换为GIF格式。不用担心&#xff…

65.乐理基础-打拍子-前附点、后附点

内容来源于&#xff1a;三分钟音乐社 上一个内容&#xff1a;前八后十六、前十六后八拍子-CSDN博客 前附点指的是一个附点八分音符加一个十六分音符的节奏型&#xff0c;如图1。 后附点指的是一个十六分音符加一个附点八分音符的节奏型&#xff0c;如图2。 前附点、后附点这两…

第三节-数据链路层与MAC地址

如果数据进行封装时&#xff0c;基于E2或者802.3标准&#xff0c;此时我们称之为是一个以太网数据帧。 不同的协议栈用于定义和管理不同网络的数据转发规则。 E2和802.3作用&#xff1a;定义帧头和帧尾的格式 数据&#xff1a;对于下层的每个层级而言&#xff0c;上层所反馈…

鸿蒙开发(二)- 鸿蒙DevEco3.X开发环境搭建

上篇说到&#xff0c;鸿蒙开发目前势头旺盛&#xff0c;头部大厂正在如火如荼地进行着&#xff0c;华为也对外宣称已经跟多个厂商达成合作。目前看来&#xff0c;对于前端或客户端开发人员来说&#xff0c;掌握下鸿蒙开发还是有些必要性的。如果你之前是从事Android开发的&…

C语言字符串知识点和算法总结

目录 一、字符串遍历 1、字符串和字符数组 2、获取字符串长度 3、字符串遍历 4、大小写转换 5、字符串数组 二、字符串拷贝 三、字符串比较 四、字符串分割 五、字符串翻转 1、题目详解 2、算法详解 3、源码剖析 六、回文串 1、定义 2、例题讲解 3、算法详解 …

子网掩码与IP段计算

一.什么叫子网掩码&#xff1a; 子网掩码(subnet mask)又叫网络掩码、地址掩码、子网络遮罩&#xff0c;它用来指明一个IP地址的哪些位标识的是主机所在的子网&#xff0c;以及哪些位标识的是主机的位掩码。子网掩码不能单独存在&#xff0c;它必须结合IP地址一起使用。 子网掩…

【开源】基于Vue+SpringBoot的班级考勤管理系统

目录 一、摘要1.1 项目介绍1.2 项目录屏 二、功能模块2.1 系统基础支持模块2.2 班级学生教师支持模块2.3 考勤签到管理2.4 学生请假管理 三、系统设计3.1 功能设计3.1.1 系统基础支持模块3.1.2 班级学生教师档案模块3.1.3 考勤签到管理模块3.1.4 学生请假管理模块 3.2 数据库设…

深入理解 C# 中的字符串比较:String.CompareTo vs String.Equals

深入理解 C# 中的字符串比较&#xff1a;String.CompareTo vs String.Equals 在处理字符串时&#xff0c;了解如何正确比较它们对于编写清晰、有效和可靠的 C# 程序至关重要。本文将深入探讨 C# 中的两个常用字符串比较方法&#xff1a;String.CompareTo 和 String.Equals&…

沃通中小微企业SSL优惠专场,DV SSL证书降幅35%

沃通CA助力中小微企业数字化安全发展&#xff0c;推出“中小微企业SSL优惠专场”&#xff0c;深受中小微企业青睐的超快SSL系列证书特惠来袭&#xff0c;降幅达35%&#xff01;实现HTTPS加密、维护企业数据传输安全&#xff0c;满足法律法规对数据安全保护的基本要求&#xff0…