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
相关产品推荐
相关产品推荐

