[![在此处输入图像描述][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;
}
}
};
关于javascript - 如何删除 redux reducer 中的购物车项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60129586/