React Redux中store.dispatch生效但useDispatch调用时state异常原因及解决
原因分析
combineReducers的工作机制决定了每个子reducer仅能接收到全局state中自己负责的分片内容:你配置的combineReducers({notes: noteReducer, filter: filterReducer}),意味着全局state结构为{notes: 子reducer返回值, filter: filterReducer返回值},noteReducer的入参state默认就只能拿到全局notes分片的内容,不会包含全局filter字段。- 首次dispatch看似正常是错误初始state导致的假象:你给noteReducer设置的初始state是包含
notes数组和filter字段的对象,第一次触发NEW_NOTEaction时,noteReducer拿到的就是这个初始对象,state.notes能正常取值,执行concat后返回了新的数组,此时noteReducer负责的notes分片直接被替换为这个数组。 - 组件内调用时state变成数组是必然结果:首次action执行完成后,noteReducer对应的分片已经从对象变为数组,第二次触发
NEW_NOTE时入参state就是这个数组,取state.notes会得到undefined,调用concat直接报错,导致创建note失败。
解决方案
两步修正noteReducer的逻辑即可:
- 修正初始state结构,noteReducer仅负责管理notes数组,不需要携带filter字段,直接用数组作为初始值:
// 修正后的初始state const initialState = [ { content: "reducer defines how redux store works", important: true, id: 1, }, { content: "state of store can contain any data", important: false, id: 2, }, ]
- 修正
NEW_NOTE分支的返回逻辑,入参state本身就是notes数组,不需要再取state.notes:
case "NEW_NOTE": console.log("state", state); return state.concat(action.data);
内容的提问来源于stack exchange,提问作者Andy Li
相关产品推荐
相关产品推荐

