Я пытаюсь создать простое промежуточное ПО Redux в моем приложении React Redux Electron, которое использует Thunk и connected-react-router
.
В myMiddleware.js
нам нужен доступ к хранилищу Redux и функции dispatch
, чтобы отправить некоторые действия. Однако getState
и dispatch
равны undefined
, как показано в приведенном ниже коде.
Как правильно обращаться к ним обоим в пользовательском промежуточном программном обеспечении Redux?
Github Repo: https://github.com/nyxynyx/accessing-store-dispatch-from-redux-middleware
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")
);
Using
- connected-react-router@6.8.0
- react-dom@16.13.1
- react-redux@7.2.0
- react-router-dom@5.1.2
- react-router@5.1.2
- react@16.13.1
- redux-localstorage@0.4.1
- redux-thunk@2.3.0
- redux@4.0.5
- Узел v14.0.0