我使用react和redux创建了一个简单的添加到购物车功能。添加到购物车工作正常,但从购物车中删除则无效。
我的代码:
actions.js
import axios from 'axios';
export const ADD_CART = "ADD_CART";
export const REMOVE_CART = "REMOVE_CART";
export const BASE_API_URL = "http://localhost:3030";
export function addToCart(item) {
console.log(window.localStorage.getItem('WCToken'))
console.log(window.localStorage.getItem('WCTrustedToken'))
var headers = {
'Content-Type': 'application/json',
'WCToken': window.localStorage.getItem('WCToken'),
'WCTrustedToken': window.localStorage.getItem('WCTrustedToken')
}
var args = {
"orderItem": [
{
"productId": "12262",//item.uniqueID, //working for 12262
"quantity": "1"
}
]
};
var data = {headers: headers, data: args};
axios.post(BASE_API_URL + "/cart", data).then(res => console.log(res))
.catch(err => console.log(err));
return {
type: ADD_CART,
payload: item
};
}
export function removeFromCart(cartList, id) {
return {
type: REMOVE_CART,
payload: cartList.filter(i => i.orderItemId!== id)
};
}
reducer.js
import {ADD_CART, REMOVE_CART} from "../actions";
const INITIAL_STATE = {
cartDetail: [],
viewCartDetail: [],
};
export default function (state = INITIAL_STATE, action) {
switch (action.type) {
case ADD_CART:
return {
...state,
cartDetail: [...state.cartDetail, action.payload]
};
case REMOVE_CART:
return {
...state,
cartDetail: action.payload
};
default:
return state;
}
}
现在这是我下面的代码,我在其中实现了删除购物车功能。
miniShoppingCart.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { removeFromCart, viewCart } from '../actions/actions';
import { Link } from "react-router-dom";
class Cart extends Component {
render() {
/**
* this.props.cart is populated through the redux store and mapStateToProps
* this.props.removeFromCart is added through mapDispatchToProps
*/
const cartList = (
<div className="container">
<div className="row">
{this.props.cart.map(item => {
return (
<div key={item.orderItemId} className="col-md-2 cart-container">
<p>
Price : {item.unitPrice}{" "}
{item.currency}
</p>
<p>{item.orderItemId}</p>
<button onClick={() => this.props.removeFromCart(this.props.cart, item.orderItemId)}>
Remove
</button>
</div>
);
})}
</div>
</div>
);
return (
this.props.cart.length > 0 ?
(<div>
<p>Items in the Cart</p>
<div className="cart">
{
cartList
}
<button className="btn btn-primary float-right"><Link to={`/cart`}>View Cart</Link></button>
</div>
</div>) : (
<p>Your cart is empty</p>
)
);
}
}
const mapStateToProps = (state) => {
return {
cart: state.fashion.viewCartDetail
};
};
const mapDispatchToProps = (dispatch) => {
return bindActionCreators({
removeFromCart: removeFromCart,
}, dispatch)
};
export default connect(mapStateToProps, mapDispatchToProps)(Cart);
我不知道自己做错了什么,但这不允许我从购物车中删除。谁能帮我解决这个问题。如果有人可以为我提供解决此问题的见解,我将不胜感激。谢谢