我想使用redux-localstorage npm模块在localstorage中持久化redux stora。问题在于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'.
答案 0 :(得分:0)
而不是:
import { persistState } from "redux-localstorage";
试
import * as persistState from "redux-localstorage";
此外,您不需要创建类型定义文件......