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

TypeScript搭配Redux时reducer导出的RootState导入失败问题求助

问题原因及修复方案

你代码里有3个核心错误导致编译失败:

  • reducers文件只导出了RootState类型,没有导出实际的根reducer函数,同时定义reducer的对象语法缺逗号
  • 你用.js后缀的store文件导入TypeScript类型,普通JS文件无法识别TS类型导入,会直接判定该导出不存在
  • createStore第一个参数传错,RootState是类型声明(运行时会被抹除不存在),需要传入实际的reducer函数

修正后的代码

reducers/index.ts

import { combineReducers } from "redux";
import user from "./user";
import account from "./account";

const allReducers = combineReducers({
  user: user,
  account: account
});

export type RootState = ReturnType<typeof allReducers>
// 新增导出根reducer
export default allReducers;

store.ts(把原来的store.js改后缀为ts)

import { createStore } from "redux";
// 同时导入根reducer和类型
import allReducers, { RootState } from '../reducers/index'

function saveToLocalStorage(state: RootState) {
  try {
    const serializedState = JSON.stringify(state);
    localStorage.setItem("state", serializedState);
  } catch (e) {
    console.log(e);
  }
}

function loadFromLocalStorage(): RootState | undefined {
  try {
    const serializedState = localStorage.getItem("state");

    if (serializedState == null) {
      return undefined;
    }
    // 给反序列化的结果加类型断言
    return JSON.parse(serializedState) as RootState;
  } catch (e) {
    console.log(e);
    return undefined;
  }
}

const savedState = loadFromLocalStorage();

const store = createStore(
  allReducers, // 第一个参数传实际的reducer函数
  savedState,
  window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);

store.subscribe(() => saveToLocalStorage(store.getState()));

export default store;

如果你的TS配置开启了importsNotUsedAsValues校验,把类型导入改为import type { RootState } from '../reducers/index'即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 09:45:01