Redux Toolkit报错:Store无有效Reducer,求错误定位与修复方案
问题分析与修复方案
错误根源
你遇到的「Store没有有效的reducer」报错,核心问题在handleCart reducer中:Redux reducer必须在任何情况下都返回一个状态值,而你的handleCart在default分支执行break后没有返回原state,导致函数最终返回undefined,被combineReducers判定为无效reducer。
另外还有两个潜在问题:
ADDITEM和REMOVEITEM是硬编码的字符串,没有定义为常量,容易出现拼写错误case分支里的break完全多余,因为return语句已经终止了函数执行
修复后的handleCart代码
// 定义action type常量,避免拼写错误 const ADDITEM = 'ADDITEM'; const REMOVEITEM = 'REMOVEITEM'; const cart = []; const handleCart = (state = cart, action) => { const product = action.payload; switch (action.type) { case ADDITEM: // 检查商品是否存在 const exist = state.find(x => x.id === product.id); if (exist) { return state.map(x => x.id === product.id ? {...x, qty: x.qty + 1} : x, ); } else { return [ ...state, { ...product, qty: 1, }, ]; } case REMOVEITEM: const exist1 = state.find(x => x.id === product.id); if (exist1.qty === 1) { return state.filter(x => x.id !== exist1.id); } else { return state.map(x => x.id === product.id ? {...x, qty: x.qty - 1} : x, ); } // 核心修复:default分支必须返回原状态 default: return state; } }; export default handleCart;
其他验证点
你的store和rootReducers代码是正确的:
configureStore正确传入了rootReducerscombineReducers也正确组合了handleCartreducer
只要修复handleCart的返回值问题,报错就会消失。
内容的提问来源于stack exchange,提问作者Khuong Viet Tai
相关产品推荐
相关产品推荐

