我已经有一段时间了,这个问题我似乎无法解决。我的Web应用程序运行良好,直到几周前当我想添加一些功能时开始出现此错误。我不知道问题可能是什么,因为我还是ReactJS的新手,即使尝试将其重置回上一个工作提交,问题仍然存在。我需要帮助来解决它。我不断收到错误消息:
TypeError:无法读取未定义的属性“ reduce”
每次我运行我的应用程序时。它表示错误出现在我的选择器文件中,该文件位于下面的文件中,并且具体位于 selectCartItemsCount 块中。
import { createSelector } from 'reselect';
const selectCart = (state) => state.cart;
export const selectCartItems = createSelector(
[selectCart],
(cart) => cart.cartItem
);
export const selectCartHidden = createSelector(
[selectCart],
(cart) => cart.hidden
);
export const selectCartItemsCount = createSelector([selectCartItems], (cartItems) =>
cartItems.reduce(
(accumulatedQuantity, cartItem) =>
accumulatedQuantity + cartItem.quantity,
0
)
);
我将此选择器导出到如下所示的组件中:
import React from 'react';
import { connect } from 'react-redux';
import { createStructuredSelector } from 'reselect';
import { toggleCartHidden } from '../../Redux/Cart/cart.actions';
import { selectCartItemsCount } from '../../Redux/Cart/cart.selectors';
import { ReactComponent as ShoppingIcon } from '../../Assets/shopping-bag.svg';
import './cart-icon.scss';
const CartIcon = ({ toggleCartHidden, itemCount }) => (
<div className="cart-icon" onClick={toggleCartHidden}>
<ShoppingIcon className="shopping-icon" />
<span className="item-count">{itemCount}</span>
</div>
);
const mapSateToProps = createStructuredSelector({
itemCount: selectCartItemsCount,
});
const mapDispatchToProps = (dispatch) => ({
toggleCartHidden: () => dispatch(toggleCartHidden()),
});
export default connect(mapSateToProps, mapDispatchToProps)(CartIcon);
我的购物车减速器看起来像这样:
import CartActionTypes from './cart.types';
import { addItemToCart, removeItemFromCart } from './cart.utils';
const INITIAL_STATE = {
hidden: true,
cartItems: [],
};
const cartReducer = (state = INITIAL_STATE, action) => {
switch (action.type) {
case CartActionTypes.TOGGLE_CART_HIDDEN:
return {
...state,
hidden: !state.hidden,
};
case CartActionTypes.ADD_ITEMS:
return {
...state,
cartItems: addItemToCart(state.cartItems, action.payload),
};
case CartActionTypes.REMOVE_ITEM:
return {
...state,
cartItems: removeItemFromCart(state.cartItems, action.payload),
};
case CartActionTypes.CLEAR_ITEM_FROM_CART:
return {
...state,
cartItems: state.cartItems.filter(
(cartItem) => cartItem.id !== action.payload.id
),
};
default:
return state;
}
};
export default cartReducer;
用于向购物车添加商品的功能是:
export const addItemToCart = (cartItems, cartItemToAdd) => {
const existingCartItem = cartItems.find(
(cartItem) => cartItem.id === cartItemToAdd.id
);
if (existingCartItem) {
return cartItems.map((cartItem) =>
cartItem.id === cartItemToAdd.id
? { ...cartItem, quantity: cartItem.quantity + 1 }
: cartItem
);
}
return [...cartItems, { ...cartItemToAdd, quantity: 1 }];
};