【发布时间】: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