我创建了一个商店,并努力寻找语法,以便在"Cart"中乘以产品的数量。我已经设法"添加"到cart"产品却没有更新数量添加的产品。每次我点击"addToCart",它都会添加产品。我正在使用redux,所以我知道我应该在reducer文件中编写额外的代码。我的reducer文件代码如下:
import { ADD_TO_CART } from './constants'
import { REMOVE_FROM_CART } from './constants'
const initialState = {
cart: [],
}
const ShoppinReducer = (state = initialState, action) => {
switch (action.type) {
case ADD_TO_CART:
const newCart = [...state.cart]
newCart.push(action.payload)
return {
...state,
cart: newCart
}
case REMOVE_FROM_CART:
const cart = [...state.cart]
const updatedCart = cart.filter(item => item.id !== action.payload.id)
return {
...state,
cart: updatedCart
}
default:
return state
}
}
export default ShoppinReducer
和我的"Cart"组件如下:
import React, { Component } from "react"
import { Card, CardBody, CardHeader, CardTitle, Row, Col } from "reactstrap"
import PanelHeader from "components/PanelHeader/PanelHeader.js"
import { connect } from "react-redux";
import { removeCart} from "../redux/actions";
class Cart extends Component {
removeFromCart = (product) => {
const cartProducts = this.props.cart
const updatedCartProducts = cartProducts.filter(item => item.id !== product.id);
}
render () {
const cartProducts = this.props.cart
return (
<>
<PanelHeader size="sm" />
<div className="content">
<Row>
<Col xs={12}>
<Card>
<CardHeader>
<CardTitle tag="h4">Products List</CardTitle>
</CardHeader>
<CardBody>
<table class="table table-striped table-hover">
<thead>
<tr>
<th scope="col"><strong>#</strong></th>
<th scope="col"><strong>Name</strong></th>
<th scope="col"><strong>Code Item</strong></th>
<th scope="col"><strong>Quantity</strong></th>
<th scope="col"><strong>Price Total</strong></th>
</tr>
</thead>
<tbody>
{cartProducts.length > 0 && cartProducts.map((cartProduct, index) => (
<tr key={cartProduct.id}>
<th scope="row">{index +1}</th>
<td>{cartProduct.title}</td>
<td>{cartProduct.code}</td>
<td>{cartProduct.quantity}</td>
<td>{cartProduct.price}</td>
<td><button onClick ={() => this.props.removeCart(cartProduct)} className="btn btn-danger cart-button px-4">Remove</button></td>
</tr>))}
</tbody>
</table>
</CardBody>
</Card>
</Col>
</Row>
</div>
</>
)
}
}
const mapStateToProps = (state)=> {
return {
cart: state.cart
}
}
const mapDispatchToProps = (dispatch) => {
return {
removeCart: (product) => {dispatch(removeCart(product))}
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Cart);
记住"addToCart"按钮生活在其他组件,然而,我张贴了"Cart"组件,以显示如何构造"Cart"啊!提前感谢!
在将任何商品推入购物车之前,您需要检查该商品是否已经存在于购物车中,如果存在则应该更新数量。您可以在您的减速器中重写ADD_TO_CART
的情况如下:
const initialState = {
cart: [],
}
const ShoppinReducer = (state = initialState, action) => {
switch (action.type) {
case ADD_TO_CART:
let newCart = [...state.cart]
let itemIndex = state.cart.findIndex(obj=>obj.id===action.payload.id)
let currItem = state.cart[itemIndex]
if(currItem){
currItem.quantity = parseInt(currItem.quantity) + 1
state.cart[itemIndex] = currItem
newCart = [...state.cart]
}
else{
newCart = newCart.concat(action.payload)
}
return {
cart: newCart
}
case REMOVE_FROM_CART:
const cart = [...state.cart]
const updatedCart = cart.filter(item => item.id !== action.payload.id)
return {
...state,
cart: updatedCart
}
default:
return state
}
}
希望我正确理解了你的问题。我假设你的购物车状态是这样的
cart: [
{itemId: '1', quantity: 1, price: 100, ...},
{itemId: '2', quantity: 1, price: 200, ...}
]
问题是,您现有的addToCart操作只会将一个项目推到数组的末尾,而不会检查这个项目是否已经存在于购物车中。最终购物车会像
一样结束
cart: [
{itemId: '1', quantity: 1, price: 100, ...},
{itemId: '2', quantity: 1, price: 200, ...},
{itemId: '1', quantity: 1, price: 100, ...}
]
所以你需要检查你是添加一个新项目还是一个现有的项目,如果它是一个现有的项目,你需要更新现有的项目数量,而不是把它推入数组。
您可以在执行ADD_TO_CART
操作时检查该项目是否已经在列表中。可以是
const alreadyInList = state.cart.find(item => item.id === action.payload.id);
let newCart;
if (alreadyInList) { // increments quantity if item already in list
newCart = state.cart.map(item => {
if (item.id === action.payload.id) {
return {..item, quantity: item.quantity + 1};
} else {
return item;
}
});
} else { // adds item to the end if it's not already in the list
newCart = [...state.cart, payload.action];
}
return {..state, cart: newCart};
然而,JavaScript数组并不是这种操作的合适数据结构。如果使用的对象的键是产品id,值是产品本身,那就更好了。这样你就可以检查一个项目是否已经存在,并更有效地更新它。
边注:
在映射列表
之前检查cartProducts的长度{cartProducts.length > 0 && cartProducts.map((cartProduct, index) => (...
你不需要那样做,只要cartProducts.map((cartProduct, index) => (...
就足够了。
另外,你可以看看react钩子和redux工具箱。这两种方法都有助于减少样板文件。
最后,下面的代码运行良好。我把它贴出来只是以防有人需要它作为将来的参考!
import { ADD_TO_CART } from './constants'
import { REMOVE_FROM_CART } from './constants'
// import { ADD_QUANTITY} from './constants'
// import { SUB_QUANTITY} from './constants'
// import { EMPTY_CART} from './constants'
const initialState = {
cart: [],
}
const ShoppinReducer = (state = initialState, action) => {
switch (action.type) {
case ADD_TO_CART:
let newCart = [...state.cart]
let itemIndex = state.cart.findIndex(obj=>obj.id===action.payload.id)
let currItem = state.cart[itemIndex]
if(currItem){
currItem.quantity = parseInt(currItem.quantity) + 1
state.cart[itemIndex] = currItem
newCart = [...state.cart]
}
else {
newCart = newCart.concat(action.payload)
}
return {
cart: newCart
}
case REMOVE_FROM_CART:
const cart = [...state.cart]
const updatedCart = cart.filter(item => item.id !== action.payload.id)
return {
...state,
cart: updatedCart
}
default:
return state
}
}
export default ShoppinReducer
正如@spiritWalker所说,您必须在reducer中实现该逻辑。我给你举个例子:
case ADD_TO_CART:
const newCart = [...state.cart]
const index = newCart.findIndex((item) => item.id == action.payload.id)
// If index is -1, no similar items were found so we
// add the item to the cart.
// Otherwise, the index of the item is returned and we use
// it to update the quantity property of the existing item.
if (index == -1) {
newCart.push(action.payload)
} else {
newCart[index].quantity++
}
return {
...state,
cart: newCart
}
另外,我建议您尝试一下Redux Toolkit Package,它从Redux中抽象了许多逻辑和样板,可以使您的代码更精简、更容易。