应该" next"总是在Redux中间件中最后调用?

时间:2018-05-15 15:05:29

标签: redux flutter

tl; dr:在Redux中间件功能中,调用next完成更新商店后是否可以发送新动作?

我使用Flutterbuilt-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。还有另一个中间件功能,它将监听该操作并请求第一个故事的详细信息。当这些细节到来时,它会请求下一个故事,依此类推,直到所有内容都更新。

我想知道的是我是否可以这样做:

// 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 个答案:

答案 0 :(得分:4)

是的,没关系 - 中间件可以在调度动作时字面任何想要的东西。这包括修改/记录/延迟/交换/忽略原始操作,以及调度其他操作。