[![在此处输入图片描述] [1]] [1]我是ReactJS和Redux的新手。在我的应用程序中,我具有显示所有CartItems的CartPage以及用于删除任何Cart项目的Remove按钮。
下面是我的代码片段,用于减少器来删除购物车商品,但是此代码似乎不起作用。
下面我要删除数组内的customerCartItem我如何删除对我有帮助
任何人都可以帮助我如何实现这一目标
//action
export const deleteCustomerCartSuccess = payload => ({
payload,
type: constants.CUSTOMER_CART_DELETE_SUCCESS,
})
import * as constants from '../constants/CartPage';
const initialState = {
customerCartDetails: {},
id: ''
};
const reducer = (state = initialState, action) => {
switch (action.type) {
case constants.CUSTOMER_CART_DETAILS_SUCCESS: {
return {
...state,
customerCartDetails: action.payload.data,
};
}
case constants.CUSTOMER_CART_DELETE_SUCCESS: {
console.log('REMOVE_REDUCER', action.payload, state.customerCartDetails.filter(item => item.id !== action.payload.id));
return {
...state,
customerCartDetails: state.customerCartDetails.CustomerCartItem.filter(item => item.id !== action.payload.id)
};
}
default: {
return state;
}
}
};
//Component
removeCartItem(index) {
const { deleteCustomerCartSuccess } = this.props;
deleteCustomerCartSuccess(index)
}
答案 0 :(得分:2)
几件事:
// Create a types.js to hold all your action constants
import { CUSTOMER_CART_DETAILS_SUCCESS, CUSTOMER_CART_DELETE_SUCCESS } from './types'
// Not necessary, but if you'll be logging a lot, consider destructuring
const { log } = console;
const initialState = {
// This should be an array, not an object, if you'll be using the filter method
customerCartItem: [],
// When initializing, make sure to set to initial state to empty arrays, objects and null values
id: null
};
const reducer = (state = initialState, action) => {
// Destructure these two from the action object
const { type, payload } = action;
switch (type) {
case CUSTOMER_CART_DETAILS_SUCCESS: {
log('CUSTOMER_CART_DETAILS_SUCCESS', payload.data);
return {
...state,
customerCartItem: payload.data,
};
}
case CUSTOMER_CART_DELETE_SUCCESS: {
log('REMOVE_REDUCER', payload);
return {
...state,
// After your edit:
customerCartItem: state.customerCartItem.filter(item => item.id !== payload.id)
};
}
default: {
return state;
}
}
};
答案 1 :(得分:0)
如果您想从购物车中移除所有商品
在减速器中
const initialState = {
items: {},
totalAmount: 0,
};
在开关盒中
case CLEAR_CART:
return state={ items: {}, totalAmount: 0, }
这是来自行动
export const clearCart = () => {
return {
type: CLEAR_CART
}
}