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

如何在Redux Toolkit的configureStore中直接获取根reducer类型?

解决方案

你想要的效果完全可以实现,不需要额外调用combineReducers,直接通过store实例的getState方法推导根状态类型即可,这也是Redux Toolkit官方推荐的标准写法:

import { configureStore } from "@reduxjs/toolkit";
import testSlice from "./testSlice";
import userSlice from "./userSlice";

export const store = configureStore({
  reducer: {test: testSlice, user: userSlice},
});

// 直接从store.getState的返回值类型推导RootState
export type RootState = ReturnType<typeof store.getState>
// 通常还会配套定义Dispatch类型方便后续使用
export type AppDispatch = typeof store.dispatch

原理解释

你在configureStore的reducer参数中直接传入切片组成的对象时,Redux Toolkit内部会自动调用combineReducers生成根reducer,不需要你手动执行这一步。store.getState的返回值就是根reducer的返回结果,所以直接取它的返回类型就能得到完整的RootState类型,完全符合你的需求。你之前构想的store.getReducer()属于不存在的API,用getState的返回类型就能达到同样的效果。

内容的提问来源于stack exchange,提问作者Francis James Dela Cruz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 07:09:01