【发布时间】:2017-05-01 04:50:21
【问题描述】:
我想使用 redux-localstorage npm 模块将 redux stora 持久化到 localstorage 中。问题在于 TypeScript,因为 redux-localstorage 没有类型定义。
所以我在redux-localstorage.ts 中编写了自定义类型定义:
declare module 'redux-localstorage' {
module ReduxLocalStorage {
export function persistState<A> (): any;
}
export = ReduxLocalStorage;
}
当我在 store.ts 中创建一个 redux 商店时:
import { createStore, applyMiddleware, compose } from "redux";
import { syncHistoryWithStore, routerMiddleware } from "react-router-redux";
import { persistState } from "redux-localstorage";
import { browserHistory } from "react-router";
// Middleware
import logger from "./middleware/logger";
let ReduxThunk = require("redux-thunk").default;
// Reducers
import reducers from "./reducers/main";
export default function configureStore() {
const createStoreWithMiddleware: any = compose(
applyMiddleware(
ReduxThunk,
logger,
routerMiddleware(browserHistory)
),
persistState(),
window.devToolsExtension ? window.devToolsExtension() : f => f
)(createStore);
const store = createStoreWithMiddleware(reducers);
return {
store,
history: syncHistoryWithStore(browserHistory, store)
};
}
当我编译项目时,一切似乎都很好,但是当我尝试在 Chrome 中加载我的应用程序时,我收到以下错误:
store.ts:21 Uncaught TypeError: redux_localstorage_1.persistState is not a function(…)configureStore @ store.ts:21(anonymous function) @ main.tsx:23__webpack_require__ @ bootstrap a9a3afb…:50(anonymous function) @ main.bundle.js?a9a3afb…:6__webpack_require__ @ bootstrap a9a3afb…:50webpackJsonpCallback @ bootstrap a9a3afb…:21(anonymous function) @ main.bundle.js?a9a3afb…:1
类型声明似乎至少以某种方式起作用,就像在我写 redux-localstorage.ts 定义之前一样,我在项目构建时遇到了以下错误:
ERROR in ./src/store.ts
(3,30): error TS2307: Cannot find module 'redux-localstorage'.
【问题讨论】:
-
我发现了问题,导入语句不正确。我应该从“redux-localstorage”导入一个默认成员,比如 import persistState;,而不是我在代码中的成员导入。作为 redux-localstorage 导出的 persistState 函数作为默认导出。但是这样改,我得到一个 TS 错误
error TS2349: Cannot invoke an expression whose type lacks a call signature. -
您解决了这个问题吗?即使使用打字模块npmjs.com/package/@types/redux-localstorage,我也有同样的问题
-
很遗憾没有,目前在没有本地存储的情况下使用。
标签: typescript redux typescript-typings