【发布时间】:2021-10-14 16:33:02
【问题描述】:
export let store: any; 中的 store 的正确类型是什么,而不是 any?考虑到我在最后一行使用了@ts-igore。我该怎么做才能摆脱 TypeScript 错误呢?
我在前三行中提到了我在这个项目中使用的样板。这是 Next.js 项目 + TypeScript + redux-presist 的一部分。
// ./stores/store.ts
// Boilerplate for Redux + Next.js: https://github.com/vercel/next.js/tree/canary/examples/with-redux-wrapper
// Boilerplate for Redux Persist: https://github.com/fazlulkarimweb/with-next-redux-wrapper-redux-persist/blob/master/store/store.js
// For more information check next-redux-wrapper: https://github.com/kirill-konshin/next-redux-wrapper
import {
createStore,
applyMiddleware,
combineReducers,
Middleware,
} from 'redux';
import { createWrapper } from 'next-redux-wrapper';
import thunkMiddleware from 'redux-thunk';
import auth from './auth/reducer';
import userData from './user/reducer';
import userChallenges from './userChallenges/reducer';
import challenges from './challenges/reducer';
// Binding middleware
const bindMiddleware = (middleware: Middleware[]) => {
if (process.env.NODE_ENV !== 'production') {
const { composeWithDevTools } = require('redux-devtools-extension');
return composeWithDevTools(applyMiddleware(...middleware));
}
return applyMiddleware(...middleware);
};
// Combining all reducers
const combinedReducer = combineReducers({
auth,
userData,
userChallenges,
challenges,
});
export let store: any;
const makeStore = ({ isServer }: { isServer: boolean }) => {
if (isServer) {
//If it's on server side, create a store
return createStore(combinedReducer, bindMiddleware([thunkMiddleware]));
} else {
//If it's on client side, create a store which will persist
const { persistStore, persistReducer } = require('redux-persist');
const storage = require('redux-persist/lib/storage').default;
const persistConfig = {
key: 'nextjs',
whitelist: ['auth', 'userData'], // only these reducers will be persisted, add other reducers if needed
storage, // if needed, use a safer storage
};
const persistedReducer = persistReducer(persistConfig, combinedReducer); // Create a new reducer with our existing reducer
store = createStore(persistedReducer, bindMiddleware([thunkMiddleware])); // Creating the store again
store.__persistor = persistStore(store); // This creates a persistor object & push that persisted object to .__persistor, so that we can avail the persistability feature
return store;
}
};
// Export the wrapper & wrap the pages/_app.js with this wrapper only
// @ts-ignore
export const wrapper = createWrapper(makeStore);
【问题讨论】:
标签: reactjs typescript redux next.js redux-persist