使用Redux Toolkit的addToCart时出现Cannot read properties of undefined错误
解决 "Cannot read properties of undefined (reading 'push')" 报错
问题根源
你遇到的报错是因为Redux store中state.cart.items未被正确访问到。当你把initialState设为对象{items: []}时,你的cart state结构是嵌套对象,但如果组件获取state时路径错误(比如直接取state.items而非state.cart.items),就会导致items为undefined,调用push时触发错误。而当初始状态设为数组时,state本身就是数组,state.push自然能正常执行。
修复步骤
1. 确认Store配置正确
确保你的cart reducer被挂载到cart键下(对应slice的name: 'cart'):
import { configureStore } from '@reduxjs/toolkit'; import cartReducer from './path/to/cartSlice'; export const store = configureStore({ reducer: { cart: cartReducer, // 必须用cart作为键名 }, });
2. 修正组件中的state访问路径
在使用useSelector获取购物车数据时,要正确指向state.cart.items:
import { useSelector, useDispatch } from 'react-redux'; import { addToCart } from './path/to/cartSlice'; const YourComponent = () => { const dispatch = useDispatch(); // 正确获取items数组 const cartItems = useSelector(state => state.cart.items); const handleAddToCart = (item) => { dispatch(addToCart(item)); }; // ...其他组件逻辑 };
3. 检查Provider包裹
确认你的应用根组件已经被Redux的Provider包裹,确保store能被全局访问:
import { Provider } from 'react-redux'; import { store } from './path/to/store'; import App from './App'; ReactDOM.createRoot(document.getElementById('root')).render( <Provider store={store}> <App /> </Provider> );
内容的提问来源于stack exchange,提问作者Radhe Shyam Dhabas
相关产品推荐
相关产品推荐

