我正在尝试在我的 React Redux Electron 应用程序中创建一个简单的 Redux 中间件,该应用程序使用 Thunk 和connected-react-router
.
在myMiddleware.js
中,我们需要访问 Redux 存储和dispatch
函数来发送一些操作。但是,getState
如dispatch
下面undefined
的代码所示。
在自定义 Redux 中间件中访问它们的正确方法是什么?
Github 仓库: https ://github.com/nyxynyx/accessing-store-dispatch-from-redux-middleware
中间件/myMiddleware.js
const myMiddleware = () => {
return ({ getState, dispatch }) => {
console.log(getState) // undefined
console.log(dispatch) // undefined
return next => action => {
return next(action);
}
}
}
store.js
import { createStore, applyMiddleware, combineReducers, compose } from 'redux';
import { connectRouter, routerMiddleware, push } from 'connected-react-router';
import persistState from 'redux-localstorage';
import thunk from 'redux-thunk';
import myMiddleware from './middleware/myMiddleware';
export default function configureStore(initialState, routerHistory) {
const router = routerMiddleware(routerHistory);
const actionCreators = {
push,
};
const reducers = {
router: connectRouter(routerHistory),
};
const middlewares = [myMiddleware, thunk, router];
const composeEnhancers = (() => {
const compose_ = window && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__;
if (process.env.NODE_ENV === 'development' && compose_) {
return compose_({ actionCreators });
}
return compose;
})();
const enhancer = composeEnhancers(applyMiddleware(...middlewares), persistState());
const rootReducer = combineReducers(reducers);
return createStore(rootReducer, initialState, enhancer);
}
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { ConnectedRouter } from 'connected-react-router';
import { createMemoryHistory } from 'history';
import routes from './routes';
import configureStore from './store';
const syncHistoryWithStore = (store, history) => {
const { router } = store.getState();
if (router && router.location) {
history.replace(router.location);
}
};
const initialState = {};
const routerHistory = createMemoryHistory();
const store = configureStore(initialState, routerHistory);
syncHistoryWithStore(store, routerHistory);
ReactDOM.render(
<Provider store={store}>
<ConnectedRouter history={routerHistory}>{routes}</ConnectedRouter>
</Provider>,
document.getElementById("root")
);
使用
- 连接反应路由器@6.8.0
- 反应-dom@16.13.1
- react-redux@7.2.0
- react-router-dom@5.1.2
- 反应路由器@5.1.2
- 反应@16.13.1
- redux-localstorage@0.4.1
- redux-thunk@2.3.0
- redux@4.0.5
- 节点 v14.0.0