[英]How do remove cart item in redux reducer?
[![在此處輸入圖片描述][1]][1]我是 ReactJS 和 Redux 的新手。 在我的應用程序中,我有 CartPage 顯示所有 CartItems 以及刪除按鈕以刪除任何購物車項目。
下面是我的 reducer 刪除購物車項目的代碼片段,但此代碼似乎不起作用。
下面我想刪除數組內的 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)
}
幾件事:
// 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;
}
}
};
如果您想從購物車中刪除所有商品
在減速機
const initialState = {
items: {},
totalAmount: 0,
};
在開關盒中
case CLEAR_CART:
return state={ items: {}, totalAmount: 0, }
這是來自行動
export const clearCart = () => {
return {
type: CLEAR_CART
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.