我需要在我的redux应用中使用商店增强器(来自react-redux-firebase的reactReduxFirebase)。这个增强器调度一个动作,它看起来或多或少像这样(简化得多):
const reactReduxFirebase = (next) => {
return (reducer, initialState, middleware) => {
const store = next(reducer, initialState, middleware);
store.dispatch({
type: 'DUMMY_ACTION'
});
return store;
}
}
// usage
const sagaMiddleware = createSagaMiddleware();
const middleware = [sagaMiddleware];
const store = createStore(
reducer,
initialState,
compose(
applyMiddleware(...middleware),
reactReduxFirebase
)
);
sagaMiddleware.run(sagas);
// sagas.js
function* handle(action) {
console.log(action);
}
function* saga() {
yield takeEvery('*', handle);
}
export default saga;

我希望saga能够听取所有操作和console.log他们,但它并没有抓住DUMMY_ACTION'由增强器调度,因为它在saga开始侦听之前被调度(sagaMiddleware.run(sagas);
)。从redux-saga文档来看,似乎必须在applyMiddleware之后运行saga,所以我无法在增强器之前运行saga。有没有办法使它工作,所以传奇也会从增强器中捕获一个动作?
答案 0 :(得分:0)
基于applyMiddlware
的解决方案:
import createSagaMiddleware from 'redux-saga';
import { takeEvery } from 'redux-saga/effects';
import { createStore, compose } from 'redux';
import {
reducer
} from '../reducers';
function sagaPreinitMiddleware(saga) {
return (createStore) => (reducer, preloadedState, enhancer) => {
const sagaMiddleware = createSagaMiddleware();
const store = createStore(reducer, preloadedState, enhancer);
let dispatch = store.dispatch;
const middlewareAPI = {
getState: store.getState,
dispatch: (action) => dispatch(action)
};
dispatch = compose(sagaMiddleware(middlewareAPI))(store.dispatch);
sagaMiddleware.run(saga); // run the saga
return {
...store,
dispatch
};
};
}
const reactReduxFirebase = (next) => {
return (reducer, initialState, middleware) => {
const store = next(reducer, initialState, middleware);
store.dispatch({
type: 'DUMMY_ACTION'
});
setTimeout(store.dispatch({
type: 'DUMMY_ACTION_1'
}), 100);
return store;
};
};
// usage
const middleware = [];
const store = createStore(
reducer,
0,
compose(
reactReduxFirebase,
sagaPreinitMiddleware(sagas)
)
);
// sagas.js
function* handle(action) {
console.log(action);
}
function* sagas() {
yield takeEvery('*', handle);
}
日志:
00000000: [reducer] action Object {type: "@@redux/INIT"}
00000008: [reducer] action Object {type: "DUMMY_ACTION"}
Object {type: "DUMMY_ACTION"}
00000011: [reducer] action Object {type: "DUMMY_ACTION_1"}
Object {type: "DUMMY_ACTION_1"}