【问题标题】:Mutating the shopping cart using redux-saga [closed]使用 redux-saga 改变购物车 [关闭]
【发布时间】:2021-09-07 13:10:57
【问题描述】:

我正在尝试使用 redux-saga 实现购物车。以下代码工作正常。但这对我来说不合适。每当我添加产品时,我都会改变购物车。让我知道我是否可以改进代码。如果是这样的话。

import { takeEvery, put } from 'redux-saga/effects';
import * as actions from '../action/saga.js';

function* cart(action) {
  const { product, onSuccess, onError } = action.payload;
  let cart = [];
  if (typeof window !== 'undefined') {
    if (localStorage.getItem('cart')) {
      cart = JSON.parse(localStorage.getItem('cart'));
    }
    const duplicate = cart.find(
      (item) => item._id === product._id
     );
    if (!duplicate) {
      cart.push({
        ...product,
        count: 1,
      });
    } else {
      cart = cart.map((item) =>
        item._id === product._id ? { ...item, count: item.count + 1 } : item
      );
    }
    localStorage.setItem('cart', JSON.stringify(cart));
  }
  try {
    if (onSuccess)
      yield put({
        type: onSuccess,
        payload: { cart: cart },
      });
  } catch (error) {
    if (onError) yield put({ type: onError, payload: error.message });
  }
}

export function* watchCart() {
  yield takeEvery(actions.sagaCartCallBegan.type, cart);
}

【问题讨论】:

  • 你有什么问题?您需要代码审查吗?
  • @brc-dd 好点!
  • @slideshowp2 是的,代码审查会很好!

标签: javascript reactjs redux next.js redux-saga


【解决方案1】:
if (!duplicate) {
  const newCart = [{ ...cart, product, count: 1 }];
} else {

...

然后使用 newCart:

 localStorage.setItem('cart', JSON.stringify(newCart));

...

payload: { card: newCart },

【讨论】:

    猜你喜欢
    • 2014-10-25
    • 2012-08-26
    • 2010-12-22
    • 1970-01-01
    • 2016-06-14
    • 1970-01-01
    • 2012-07-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多