减速器调度推送问题



有人能看看我的减速器,看看.push()有什么问题吗?由于某些原因,以下错误被抛出

错误类型错误:无法读取未定义(读取"推送"(的属性

但该值未定义。

Cart Reducer State = {"cartItems":[],"itemCount":0,"total":0}
Cart Reducer Action = {"type":"ADD_ITEM","payload":{"_id":"61cb88d85f499fd4563e99d3","sku":1001,"image":"blueband","title":"Wrist Band - 1 Custom Insert","description":"Band with custom photo insert included with purchase.","active":{"status":true,"display":true,"startDate":"2021-09-21T22:55:03.686Z","endDate":""},"color":"Blue","quantity":100,"price":16.99,"createdAt":"2021-12-28T21:59:52.357Z","updatedAt":"2021-12-28T21:59:52.357Z","__v":0}}
export const sumItems = (cartItems) => {
return {
itemCount: cartItems.reduce((total, prod) => total + prod.quantity, 0),
total: cartItems.reduce(
(total, prod) => total + prod.price * prod.quantity,
0
),
};
};
const cartReducer = (state, action) => {
switch (action.type) {
case "ADD_ITEM":
//check if item is in cart
if (!state.cartItems.find((item) => item._id === action.payload._id)) {
//Below is an Object
console.log(JSON.stringify(state));
console.log(JSON.stringify(action));
state.cartItem.push({
...action.payload,
quantity: 1,
});
}
return {
...state,
cartItems: [...state.cartItems],
...sumItems(state.cartItems),
};
default:
return state;
}
};
export default cartReducer;

您需要为减速器提供一个初始状态。您当前在default的情况下返回state,最初将是undefined(请检查redux dev工具(。

在reducer定义中,为state参数设置一个默认值,类似于state = {cartItems: [], itemCount: 0, total: 0}

或者你可以在一个文件中移动初始状态,比如state.js,其中包含以下内容:

export default {
cartItems: [],
itemCount: 0,
total: 0
}

然后将其导入您的减速器:

import initialState from './state';

并通过参数的默认值在reducer中设置initialState,或者只从default的情况返回initalState

default: 
return initialState;

最新更新