React Redux调用dispatch触发slice reducer返回undefined报错如何解决
问题解决方案
错误根因
报错的核心原因是FOO_BAR对应的切片reducer不符合Redux的规则:所有reducer在任何action触发时都必须返回有效值,不能返回undefined,哪怕该action不属于当前reducer的处理范围,也要显式返回原有state。
修复步骤
- 检查
FOO_BAR对应的reducer逻辑,补充switch的default默认分支
示例正确写法如下:
// 初始值不能设为undefined,可根据业务需求调整为null、空对象、空数组等 const initialFooBarState = null const fooBarReducer = (state = initialFooBarState, action) => { switch(action.type) { // 你原有业务的action处理逻辑 case 'UPDATE_FOO_DATA': return { ...state, data: action.payload } // 必须添加默认分支,所有未匹配的action都返回原state default: return state } }
- 确认reducer的初始状态已正确赋值:state参数的默认值必须显式设置,不能留空
- 检查根reducer(
./redux/reducers/index.js中的combineReducers配置),确认FOO_BAR对应的reducer导入、关联正确,没有拼写错误
额外问题修复
你当前的API请求代码存在几处小错误,建议同步修改避免后续其他报错:
- 拼写错误:
reponse.status.OK应为response.ok - 构造函数大写错误:
throw new error()应为throw new Error(error)
修正后的请求代码如下:
import store from "./store"; import foo from "./foo.js"; fetch("http://my_fantastic_api.com/fooBar/") .then((response)=>{ if (response.ok){ store.dispatch({ type:"MODIFY_XYZ" }); } }).catch(error =>{ throw new Error(error) })
优化建议
后续迭代可以使用Redux Thunk、Redux Toolkit Query这类官方推荐的异步处理方案,避免直接在业务文件里引入store实例,降低代码耦合度。
内容的提问来源于stack exchange,提问作者Alvin Cheng
相关产品推荐
相关产品推荐

