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

Redux Toolkit中useSelector的IRootState类型来源疑问

在Redux Toolkit + TypeScript中使用IRootState的正确方式

这个IRootState类型需要你自行定义,而非从第三方库直接导入。因为每个项目的Redux State结构都是自定义的,包含的切片(slice)及各自的状态结构完全由你决定,所以不存在通用的预定义IRootState。

具体定义步骤:

  1. 在Store配置文件中推导类型
    通常我们会在Redux Store的配置文件(比如app/store.ts)里,基于configureStore创建的store实例,自动推导整个RootState的类型:

    import { configureStore } from '@reduxjs/toolkit';
    // 导入你的各个slice reducer
    import usersReducer from '../features/users/usersSlice';
    import postsReducer from '../features/posts/postsSlice';
    
    // 创建store
    export const store = configureStore({
      reducer: {
        users: usersReducer,
        posts: postsReducer
        // 其他slice的reducer
      },
    });
    
    // 从store的getState方法推导RootState类型
    export type IRootState = ReturnType<typeof store.getState>;
    // 同时可以导出Dispatch类型,方便后续使用useDispatch时指定类型
    export type AppDispatch = typeof store.dispatch;
    
  2. 在组件中导入并使用
    之后在需要用useSelector的组件里,直接导入这个自定义的IRootState即可:

    import { useSelector } from 'react-redux';
    import { IRootState } from '../app/store';
    
    // 写法:指定state类型,TypeScript自动推导返回值类型
    const usersPage = useSelector((state: IRootState) => state.users.page);
    

    你提供的代码里显式指定了<IRootState, number>泛型,其实可以省略第二个泛型参数,TypeScript会根据你返回的state.users.page自动推断出它的类型是number,写法更简洁。

内容的提问来源于stack exchange,提问作者Mohammad Zourmand

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 16:06:25