tl;dr: Within a Redux middleware function, is it okay to dispatch a new action after calling next to finish updating the store?
我正在使用Flutter和built-flutter-redux构建一个HackerNews读者,基于Brian Egan的TodoMVC example . 它使用HN的Firebase支持的API来提取数据:
https://github.com/HackerNews/API
我的行为现在看起来像这样:
ActionDispatcher<Null> fetchHackerNewsTopStories;
ActionDispatcher<List<int>> fetchHackerNewsTopStoriesSuccess;
ActionDispatcher<Null> fetchHackerNewsTopStoriesFailure;
ActionDispatcher<Null> fetchNextHackerNewsItem;
ActionDispatcher<HackerNewsItem> fetchHackerNewsItemSuccess;
ActionDispatcher<Null> fetchHackerNewsItemFailure;
有一个中间件可以监听 fetchHackerNewsTopStories
操作并启动对API的调用:
MiddlewareHandler<AppState, AppStateBuilder, AppActions, Null>
createFetchHackerNewsTopStories(HackerNewsRepository service) {
return (MiddlewareApi<AppState, AppStateBuilder, AppActions> api,
ActionHandler next, Action<Null> action) {
service.fetchHackerNewsTopStories().then((ids) {
return api.actions.fetchHackerNewsTopStoriesSuccess(ids);
}).catchError(api.actions.fetchHackerNewsTopStoriesFailure);
next(action);
};
}
当它返回时,我用ID列表更新我的应用程序状态 .
在某些时候,我需要发出另一个动作, fetchNextHackerNewsItem
. 有's another middleware function that will listen for that action and request the details for the the first story. When those details arrive, it' ll请求下一个故事,依此类推,直到所有内容都更新 .
我想知道的是我是否可以这样做:
// Invoked when REST call for the list of top story IDs completes.
MiddlewareHandler<AppState, AppStateBuilder, AppActions, List<int>>
createFetchHackerNewsTopStoriesSuccess() {
return (MiddlewareApi<AppState, AppStateBuilder, AppActions> api,
ActionHandler next, Action<List<int>> action) {
next(action);
api.actions.fetchNextHackerNewsItem(); // Is this cool?
};
}
// Initiates a request for a single story's details.
MiddlewareHandler<AppState, AppStateBuilder, AppActions, Null>
createFetchNextHackerNewsItem(HackerNewsRepository service) {
return (MiddlewareApi<AppState, AppStateBuilder, AppActions> api,
ActionHandler next, Action<Null> action) {
int nextId = api.state.topStoryIds[api.state.loadedUpToIndex];
service.fetchHackerNewsItem(nextId).then((item) {
return api.actions.fetchHackerNewsItemSuccess(item);
}).catchError(api.actions.fetchHackerNewsTopStoriesFailure);
next(action);
};
}
因为 createFetchNextHackerNewsItem
依赖于应用程序的状态( api.state.topStoryIds[api.state.loadedUpToIndex]
),所以我希望它在 next(action)
调用更新商店后运行 .
在调用 next
后调用Redux中间件中的新操作是否很酷,还是某种反模式?如果它是反模式,那么实现此流程的最佳方法是什么?
1 回答
是的,没关系 - 中间件在发送动作时可以做任何想要的事情 . 这包括修改/记录/延迟/交换/忽略原始操作,以及调度其他操作 .