为了能到远方,脚下的每一步都不能|

505donkey

园龄:6年3个月粉丝:7关注:0

【React】美团案例-添加购物车实现

添加购物车实现

需求理解

  • 点击 + 号添加当前商品到购物车列表

实现步骤

  • 使用 RTK 管理新状态 cartList
  • 思路:如果添加过,只更新数量 count,没有添加过,直接push进去
  • 组件中点击时搜集数据提交 action 添加购物车

代码实现

store/modules/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
        changeActisveIndex(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)
            }
        },
        // 删除购物车
        deleteCart(state, action) {
            state.cartList = state.cartList.filter(item => item.id !== action.payload)
        }
    }
})

// 异步获取部分(解构修改方法)
const { setFoodsList, changeActisveIndex, addCart } = foodsStore.actions // 解构foodsStore方法

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

export { fetchFoodsList, changeActisveIndex, addCart }

const reducer = foodsStore.reducer

export default reducer

comonents/FoodsCategory/FoodItem/index.js

import { useDispatch } from 'react-redux'
import { addCart } from '../../../store/modules/takeaway'
import './index.scss'

const Foods = ({
  id,
  picture,
  name,
  unit,
  description,
  food_tag_list,
  month_saled,
  like_ratio_desc,
  price,
  tag,
  count
}) => {
  const dispatch = useDispatch()
  return (
    <dd className="cate-goods">
      <div className="goods-img-wrap">
        <img src={picture} alt="" className="goods-img" />
      </div>
      <div className="goods-info">
        <div className="goods-desc">
          <div className="goods-title">{name}</div>
          <div className="goods-detail">
            <div className="goods-unit">{unit}</div>
            <div className="goods-detail-text">{description}</div>
          </div>
          <div className="goods-tag">{food_tag_list.join(' ')}</div>
          <div className="goods-sales-volume">
            <span className="goods-num">月售{month_saled}</span>
            <span className="goods-num">{like_ratio_desc}</span>
          </div>
        </div>
        <div className="goods-price-count">
          <div className="goods-price">
            <span className="goods-price-unit">¥</span>
            {price}
          </div>
          <div className="goods-count">
            <span className="plus" onClick={() => dispatch(addCart(
              id,
              picture,
              name,
              unit,
              description,
              food_tag_list,
              month_saled,
              like_ratio_desc,
              price,
              tag,
              count
            ))}></span>
          </div>
        </div>
      </div>
    </dd>
  )
}

export default Foods

本文作者:505donkey

本文链接:https://www.cnblogs.com/505donkey/p/18545077

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   505donkey  阅读(43)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起