You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Redux预加载状态(preloadedState)覆盖默认reducer状态引发undefined错误问题排查

Why PreloadedState Breaks Your Reducer's Default State

Great question—let’s unpack exactly what’s happening here, because this is a common gotcha with Redux initial state!

The Core Issue: PreloadedState Overrides Reducer Defaults

First, let’s clarify how Redux handles initial state:

  • When you pass a preloadedState (your initialState variable) to createStore, Redux uses this value as the starting state for your reducers.
  • The default state you define in your reducer (state = {cartItems: []}) only kicks in if there’s no corresponding value provided in preloadedState.

In your code, you’re explicitly passing:

const initialState = { cart: {cartitems: cartItemsFromStorage} }

This means the cartReducer will receive {cartitems: [...]} as its initial state—not the default {cartItems: []} you wrote in the reducer. Since your reducer tries to access state.cartItems (with a capital I) but your preloaded state only has cartitems (lowercase i), you get the "undefined" error.

Why Your Assumption About Default State Was Wrong

You’re right that reducers have default states, but they’re only used when Redux doesn’t receive a preloaded state for that slice. Think of the reducer’s default state as a fallback—if you provide a value via preloadedState, Redux uses that instead.

The Fix

All you need to do is fix the typo in your initialState to match the key in your reducer:

const initialState = { cart: {cartItems: cartItemsFromStorage} }

Now the cartReducer will receive a state with the correct cartItems property, and your state.cartItems.find(...) line will work as expected.


内容的提问来源于stack exchange,提问作者user3491700

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.01 02:12:30