tl; dr:在Redux中间件函数中,可以在调用next完成商店更新后分派新操作吗?
我基于Brian Egan的TodoMVC示例,使用Flutter和Built -flutter-redux构建了HackerNews阅读器。它使用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;
Run Code Online (Sandbox Code Playgroud)
有一个中间件可以监听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);
};
}
Run Code Online (Sandbox Code Playgroud)
返回时,我使用ID列表更新应用的状态。
在某个时候,我需要调度另一个动作fetchNextHackerNewsItem。还有另一个中间件功能,可以监听该动作并请求第一个故事的详细信息。当这些细节到达时,它将请求下一个故事,依此类推,直到所有内容都更新为止。
我想知道的是我是否可以这样做:
// 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);
};
}
Run Code Online (Sandbox Code Playgroud)
由于createFetchNextHackerNewsItem依赖于应用程序的状态(api.state.topStoryIds[api.state.loadedUpToIndex]),因此我希望它在调用更新存储后运行next(action)。
在调用之后在Redux中间件中调度新操作是否很酷next,还是某种反模式?如果是反模式,实现此流程的最佳方法是什么?
是的,它的罚款-中间件可以做字面上什么时候一个动作被分派就是了。这包括修改/记录/延迟/交换/忽略原始操作,以及分派其他操作。
| 归档时间: |
|
| 查看次数: |
414 次 |
| 最近记录: |