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

在Redux Toolkit中能否在外部文件的reducer中直接修改state?

这种直接修改state的写法完全可行

核心原因:Redux Toolkit内置了Immer库

Redux Toolkit的createSlice(包括extraReducers里绑定的外部reducer)会自动在Immer的「可变更新」上下文里执行你的reducer逻辑。你看起来是直接修改state属性、调用questionsAdapter.setAll(state, questions),但Immer会自动把这些操作转换成符合Redux要求的不可变更新,不会破坏Redux的核心规则。

抽离reducer到单独文件是合理实践

把reducer逻辑拆到单独文件完全没问题,不管是reducers字段里的自定义reducer,还是extraReducers里绑定的异步action对应的reducer,都支持传入外部定义的函数——只要函数符合(state, action) => void的签名,和写在slice内部没有任何区别。

你的代码细节没有问题

  • 调用questionsAdapter.setAll(state, questions)是正确用法,Entity Adapter的方法本身就适配了Immer上下文,直接操作state即可。
  • 后续计算maxPossiblePoints和numQuestions时,用questionsAdapter.getSelectors().selectAll(state)能拿到更新后的列表,因为Immer会实时追踪state变化,这部分逻辑是通顺的。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 09:54:54