我遇到一个问题,增强器(在这种情况下为redux-little-router)吞下一个动作并发送一个新动作。我还有中间件需要监听这个新动作(以及它的有效负载)并在响应中调度异步动作。
这是不可能的,因为增强器是在链中的applyMiddleware之后(因为它应该是),因此调度的新操作只会通过后续增强器的调度函数。
这是一个人为的例子:
export const testMiddleware = store => next => action => {
console.log('Middleware1', action.type);
if (action.type === 'SOME_OTHER_ACTION_TYPE') {
console.log('Hurray, responded to some other action here!');
}
return next(action);
};
function testEnhancer() {
return(createStore) => (reducer, preloadedState, enhancer) => {
const store = createStore(reducer, preloadedState, enhancer);
const dispatch = (action) => {
// Swallow this action, and dispatch the replacement
if (action.type === 'SOME_ACTION_TYPE') {
console.log('testEnhancer', action.type, 'swallowing');
store.dispatch({
type: 'SOME_OTHER_ACTION_TYPE',
payload: 'some other payload'
});
return null;
}
console.log('testEnhancer', action.type, 'passing on');
return store.dispatch(action);
}
return Object.assign({}, store, {dispatch});
};
}
export default function configureStore(initialState = undefined) {
const enhancer = compose(
applyMiddleware(
thunkMiddleware,
testMiddleware
),
testEnhancer(),
DevTools.instrument()
);
这似乎是一种不可能的情况,但我找不到任何文档说增强器不应该发送动作。也许他们不应该?或者有解决方法吗?