Redux派发remaining时出错:如何修复该dispatch方法?
问题分析与修复方案
看起来你遇到的问题根源在reducer的DECK_DRAW.FETCH_SUCCESS分支里,我们一步步来梳理:
先看你当前reducer的问题代码段:
case DECK_DRAW.FETCH_SUCCESS: remaining = action.remaining; deck_id = action.deck_id; return { ...state,cards, remaining, fetchState: fetchStates.success};
这里有两个致命问题:
- 未声明变量导致的ReferenceError:你尝试给
deck_id赋值,但这个变量从未被声明过(仅在switch外声明了cards和remaining)。在严格模式下,这种操作会直接抛出错误,中断reducer执行——这就是为什么你看到Fetch Success打印后,后续流程被中断的原因。 - 未赋值的
cards变量:你声明了cards但没有给它赋值,直接放到返回的state里,会把原有的cards数组覆盖成undefined,破坏状态结构。
而且你的action创建函数fetchDrawCard里,dispatch的action根本没有传递deck_id,就算声明了deck_id,它的值也是undefined,完全没必要处理它。
修正后的Reducer代码
const deckReducer = (state = DEFAULT_DECK, action) => { switch(action.type){ case DECK.FETCH_SUCCESS: const {remaining, deck_id} = action; return{ ...state, remaining, deck_id, fetchState: fetchStates.success }; case DECK.FETCH_ERROR: return { ...state, message: action.message, fetchState: fetchStates.error }; case DECK_DRAW.FETCH_SUCCESS: // 直接从action解构需要的字段,避免额外变量声明 const { cards, remaining } = action; // 抽卡不需要修改deck_id,保留原有state的值即可 return { ...state, cards, // 用action传递的cards数组更新state remaining, // 用action传递的剩余卡牌数更新state fetchState: fetchStates.success }; case DECK_DRAW.FETCH_ERROR: console.log('Fetch Error'); return { ...state, fetchState: fetchStates.error, message: action.message // 确保错误信息存入state }; default : return state ; }; };
关键修改说明
- 移除了switch外多余的
let cards, remaining;声明,改为在需要的分支内直接从action解构字段,避免变量污染和未赋值问题。 - 去掉了
DECK_DRAW.FETCH_SUCCESS分支里对deck_id的处理——你的action里没传这个值,且抽卡操作不需要修改deck_id,直接保留原有state的值即可。 - 正确从action中取出
cards和remaining,确保state的这两个字段被正确更新。 - 在
DECK_DRAW.FETCH_ERROR分支里添加了message赋值,保证错误信息能被存储到state中,方便后续展示。
如果你的业务逻辑需要在抽卡时传递deck_id,可以在action创建函数里补充:
dispatch({ type: DECK_DRAW.FETCH_SUCCESS, cards: json.cards, remaining: json.remaining, deck_id: deck_id // 传入deck_id到action中 }) ;
但如果不需要修改deck_id,完全没必要多此一举。
这样修改后,dispatch就能正常执行,不会再因reducer的错误而中断了。
内容的提问来源于stack exchange,提问作者Devon
相关产品推荐
相关产品推荐

