You need to enable JavaScript to run this app. 如何用useSelector访问Redux store的state并解决DefaultRootState报错
优惠活动
大模型
产品
解决方案
定价
更多

如何用useSelector访问Redux store的state并解决DefaultRootState报错

报错原因

该报错是TypeScript无法识别自定义Redux store的根状态结构,默认使用了Redux内置的空类型DefaultRootState,因此无法匹配你挂载在根状态下的getName、getSomething等reducer对应的属性。


解决步骤

步骤1:在store定义文件中导出根状态类型

找到你定义store的文件,新增类型导出:

import { configureStore } from '@reduxjs/toolkit'
import { combineReducers } from 'redux'
// 你原有reducer的引入保持不变

const reducers = {
  getName,
  getSomething,
  getCollection,
  getSomethingelse
}
const rootReducer = combineReducers(reducers);

const store = configureStore({reducer : rootReducer});

// 新增以下类型导出
export type RootState = ReturnType<typeof store.getState>
export type AppDispatch = typeof store.dispatch

步骤2:修正useSelector的类型定义,两种方案二选一

方案1:每次调用useSelector时手动指定state类型

在使用useSelector的组件中引入RootState,给回调的state参数声明类型:

import { useSelector } from 'react-redux'
import type { RootState } from './store' // 替换为你的store文件实际路径

// 访问时指定state类型即可
const name = useSelector((state: RootState) => state.getName.nameList)
const something = useSelector((state: RootState) => state.getSomething.something)
方案2(更推荐):全局封装带类型的自定义hook

在store文件中直接封装适配你项目类型的专用hook,后续所有组件都用自定义hook代替原生useSelector,无需每次重复声明类型:

// store.ts 中新增代码
import { useDispatch, useSelector } from 'react-redux'
import type { TypedUseSelectorHook } from 'react-redux'

export const useAppDispatch: () => AppDispatch = useDispatch
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector

组件中直接使用即可:

import { useAppSelector } from './store'

const name = useAppSelector(state => state.getName.nameList)
const something = useAppSelector(state => state.getSomething.something)

额外校验点

请确认combineReducers的配置正确:

  • createSlice创建的setNameList切片,需要导出setNameList.reducer,作为getName对应的reducer传入reducers对象
  • 普通写法的somethingReducer需要正确默认导出,赋值给getSomething对应的key

内容的提问来源于stack exchange,提问作者Sai Krishnadas

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 03:39:03