如何检查产品是否在 redux 工具包的购物卡中重复并反应 js
how to check if a product is repeated in shopping card in redux toolkit and react js
我刚刚用 redux 工具包和 reactJs 做了一张购物卡。但是我不知道如何处理我的购物卡中重复的产品。它只是多次添加相同的产品!
我该如何处理?
shoppingCard.js
import { createSlice } from "@reduxjs/toolkit";
import { createSelector } from "reselect";
// Create Slice
const slice = createSlice({
name: "shoppingCard",
initialState: { shoppingCardList: [], loading: true },
reducers: {
addItemToCart: (state, action) => {
const pseudoId = new Date().getTime(); //generating id for cart items
state.shoppingCardList.push({
id: pseudoId,
productName: action.payload.product.name,
productId: action.payload.product.product_code,
quantity: action.payload.Quantity,
price: parseInt(action.payload.product.price),
totalPrice:
action.payload.Quantity * parseInt(action.payload.product.forosh),
});
state.loading = false;
},
removeItemFromCart: (state, action) => {
state.shoppingCardList = state.shoppingCardList.filter(
(cartItem) => cartItem.id !== action.payload.cartItemId
);
},
},
});
// console.log(slice);
// selectors
export const getShoppingCartItem = (state) => state.cart.shoppingCardList;
export const getTotalPrice = (state) => {
return state.cart.shoppingCardList.reduce((total, shoppingCardList) => {
return shoppingCardList.totalPrice + total;
}, 0);
};
export const { addItemToCart, removeItemFromCart } = slice.actions;
export default slice.reducer;
shoppingCard.jsx
import React from "react";
import CardItem from "./shoppingCardItem";
import { useSelector } from "react-redux";
import { addCommas } from "@persian-tools/persian-tools";
import { Link } from "react-router-dom";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faArrowLeft } from "@fortawesome/free-solid-svg-icons";
import { Card } from "react-bootstrap";
import {
getCartState,
getShoppingCartItem,
getTotalPrice,
} from "../store/shoppingcard";
import "../css/shoppingCard.css";
import Loader from "react-loader-spinner";
const ShoppingCard = () => {
const cartItem = useSelector(getShoppingCartItem);
const total = useSelector(getTotalPrice);
console.log("state shoppingCart", cartItem);
return (
<React.Fragment>
<Card className="fixed-top">
<Card.Body>
<Link to="/nav/products">
<FontAwesomeIcon icon={faArrowLeft} style={{ float: "left" }} />
</Link>
</Card.Body>
</Card>
<Loader
style={{
position: "fixed",
top: "50%",
left: "50%",
transform: "translate(-50%, -50%)",
zIndex: "10",
}}
visible={state.loading === true ? true : false}
type="Puff"
color="#00BFFF"
height={100}
width={100}
/>
<div style={{ height: "95vh", overflow: "scroll" }}>
<CardItem cartItem={cartItem} />
</div>
<Card className="fixed-bottom">
<Card.Body>
<div className="row">
<div style={{ textAlign: "center" }} className="col-6">
مجموع : {addCommas(total)} ریال
</div>
<div style={{ textAlign: "center" }} className="col-6">
<button className="btn btn-primary">ارسال سفارش</button>
</div>
</div>
</Card.Body>
</Card>
</React.Fragment>
);
};
export default ShoppingCard;
shoppingCardItem 的文件是这个。
shoppingCardItem.jsx
import React from "react";
import Icon from "./icon";
import { Card } from "react-bootstrap";
import { addCommas } from "@persian-tools/persian-tools";
import { useDispatch } from "react-redux";
import { removeItemFromCart } from "../store/shoppingcard";
const CardItem = ({ cartItem }) => {
const dispatch = useDispatch();
return (
<React.Fragment>
{cartItem.map((cartItem) => (
<Card className="shoppingCard" key={cartItem.productId}>
<Card.Header>نام کالا : {cartItem.productName}</Card.Header>
<Card.Body>
<div className="row" style={{ margin: "auto" }}>
<div className="col-8">
<div className="row secondary">
قیمت پایه : {addCommas(cartItem.price)} ریال
</div>
<div className="row">
تعداد کارتن سفارش شده :{cartItem.quantity}
</div>
<div className="row secondary">
مجموع : {addCommas(cartItem.totalPrice)} ریال
</div>
</div>
<div className="col-4">
<img src="" alt="picture of products" />
</div>
</div>
<div className="row m-2" style={{ float: "left" }}>
<button style={{ width: "auto" }} className="btn btn-success m-2">
+
</button>
<button style={{ width: "auto" }} className="btn btn-warning m-2">
-
</button>
<button
style={{ width: "auto" }}
className="btn btn-danger m-2"
onClick={() =>
dispatch(removeItemFromCart({ cartItemId: cartItem.id }))
}
>
<Icon />
</button>
</div>
</Card.Body>
</Card>
))}
</React.Fragment>
);
};
export default CardItem;
这些是我的 redux 和 reactjs 购物卡文件。
我想检查一个产品是否已经存在然后只更新数量而不是添加具有相同数据的另一个产品。
请检查下面的代码我已经在 shoppingCard.js 组件中添加了逻辑。
如果需要,您可以设置额外的逻辑。
addItemToCart: (state, action) => {
const pseudoId = new Date().getTime(); //generating id for cart items
//Add logic for update the existing cart items start
const existingCartItemIndex = state.shoppingCardList.findIndex(
(item) => item.productId === action.item.productId
);
const existingCartItem = store.shoppingCardList[existingCartItemIndex];
let updatedItems;
if (existingCartItem) {
//Find the index and update the items
const updateItem = {
...existingCartItem,
//extra code - add your logic
quantity: existingCartItem.quantity + action.payload.quantity,
}
updatedItems = [...state.shoppingCardList]
updatedItems[existingCartItemIndex] = updateItem;
} else {
const addObject = {
id: pseudoId,
productName: action.payload.product.name,
productId: action.payload.product.product_code,
quantity: action.payload.Quantity,
price: parseInt(action.payload.product.price),
totalPrice:
action.payload.Quantity * parseInt(action.payload.product.forosh),
};
//state.shoppingCardList.push(addObject);
updatedItems = state.shoppingCardList.concat(addObject);
}
//Add logic for update the existing cart items end
state.loading = false;
}
我刚刚用 redux 工具包和 reactJs 做了一张购物卡。但是我不知道如何处理我的购物卡中重复的产品。它只是多次添加相同的产品! 我该如何处理?
shoppingCard.js
import { createSlice } from "@reduxjs/toolkit";
import { createSelector } from "reselect";
// Create Slice
const slice = createSlice({
name: "shoppingCard",
initialState: { shoppingCardList: [], loading: true },
reducers: {
addItemToCart: (state, action) => {
const pseudoId = new Date().getTime(); //generating id for cart items
state.shoppingCardList.push({
id: pseudoId,
productName: action.payload.product.name,
productId: action.payload.product.product_code,
quantity: action.payload.Quantity,
price: parseInt(action.payload.product.price),
totalPrice:
action.payload.Quantity * parseInt(action.payload.product.forosh),
});
state.loading = false;
},
removeItemFromCart: (state, action) => {
state.shoppingCardList = state.shoppingCardList.filter(
(cartItem) => cartItem.id !== action.payload.cartItemId
);
},
},
});
// console.log(slice);
// selectors
export const getShoppingCartItem = (state) => state.cart.shoppingCardList;
export const getTotalPrice = (state) => {
return state.cart.shoppingCardList.reduce((total, shoppingCardList) => {
return shoppingCardList.totalPrice + total;
}, 0);
};
export const { addItemToCart, removeItemFromCart } = slice.actions;
export default slice.reducer;
shoppingCard.jsx
import React from "react";
import CardItem from "./shoppingCardItem";
import { useSelector } from "react-redux";
import { addCommas } from "@persian-tools/persian-tools";
import { Link } from "react-router-dom";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faArrowLeft } from "@fortawesome/free-solid-svg-icons";
import { Card } from "react-bootstrap";
import {
getCartState,
getShoppingCartItem,
getTotalPrice,
} from "../store/shoppingcard";
import "../css/shoppingCard.css";
import Loader from "react-loader-spinner";
const ShoppingCard = () => {
const cartItem = useSelector(getShoppingCartItem);
const total = useSelector(getTotalPrice);
console.log("state shoppingCart", cartItem);
return (
<React.Fragment>
<Card className="fixed-top">
<Card.Body>
<Link to="/nav/products">
<FontAwesomeIcon icon={faArrowLeft} style={{ float: "left" }} />
</Link>
</Card.Body>
</Card>
<Loader
style={{
position: "fixed",
top: "50%",
left: "50%",
transform: "translate(-50%, -50%)",
zIndex: "10",
}}
visible={state.loading === true ? true : false}
type="Puff"
color="#00BFFF"
height={100}
width={100}
/>
<div style={{ height: "95vh", overflow: "scroll" }}>
<CardItem cartItem={cartItem} />
</div>
<Card className="fixed-bottom">
<Card.Body>
<div className="row">
<div style={{ textAlign: "center" }} className="col-6">
مجموع : {addCommas(total)} ریال
</div>
<div style={{ textAlign: "center" }} className="col-6">
<button className="btn btn-primary">ارسال سفارش</button>
</div>
</div>
</Card.Body>
</Card>
</React.Fragment>
);
};
export default ShoppingCard;
shoppingCardItem 的文件是这个。
shoppingCardItem.jsx
import React from "react";
import Icon from "./icon";
import { Card } from "react-bootstrap";
import { addCommas } from "@persian-tools/persian-tools";
import { useDispatch } from "react-redux";
import { removeItemFromCart } from "../store/shoppingcard";
const CardItem = ({ cartItem }) => {
const dispatch = useDispatch();
return (
<React.Fragment>
{cartItem.map((cartItem) => (
<Card className="shoppingCard" key={cartItem.productId}>
<Card.Header>نام کالا : {cartItem.productName}</Card.Header>
<Card.Body>
<div className="row" style={{ margin: "auto" }}>
<div className="col-8">
<div className="row secondary">
قیمت پایه : {addCommas(cartItem.price)} ریال
</div>
<div className="row">
تعداد کارتن سفارش شده :{cartItem.quantity}
</div>
<div className="row secondary">
مجموع : {addCommas(cartItem.totalPrice)} ریال
</div>
</div>
<div className="col-4">
<img src="" alt="picture of products" />
</div>
</div>
<div className="row m-2" style={{ float: "left" }}>
<button style={{ width: "auto" }} className="btn btn-success m-2">
+
</button>
<button style={{ width: "auto" }} className="btn btn-warning m-2">
-
</button>
<button
style={{ width: "auto" }}
className="btn btn-danger m-2"
onClick={() =>
dispatch(removeItemFromCart({ cartItemId: cartItem.id }))
}
>
<Icon />
</button>
</div>
</Card.Body>
</Card>
))}
</React.Fragment>
);
};
export default CardItem;
这些是我的 redux 和 reactjs 购物卡文件。 我想检查一个产品是否已经存在然后只更新数量而不是添加具有相同数据的另一个产品。
请检查下面的代码我已经在 shoppingCard.js 组件中添加了逻辑。 如果需要,您可以设置额外的逻辑。
addItemToCart: (state, action) => {
const pseudoId = new Date().getTime(); //generating id for cart items
//Add logic for update the existing cart items start
const existingCartItemIndex = state.shoppingCardList.findIndex(
(item) => item.productId === action.item.productId
);
const existingCartItem = store.shoppingCardList[existingCartItemIndex];
let updatedItems;
if (existingCartItem) {
//Find the index and update the items
const updateItem = {
...existingCartItem,
//extra code - add your logic
quantity: existingCartItem.quantity + action.payload.quantity,
}
updatedItems = [...state.shoppingCardList]
updatedItems[existingCartItemIndex] = updateItem;
} else {
const addObject = {
id: pseudoId,
productName: action.payload.product.name,
productId: action.payload.product.product_code,
quantity: action.payload.Quantity,
price: parseInt(action.payload.product.price),
totalPrice:
action.payload.Quantity * parseInt(action.payload.product.forosh),
};
//state.shoppingCardList.push(addObject);
updatedItems = state.shoppingCardList.concat(addObject);
}
//Add logic for update the existing cart items end
state.loading = false;
}