首页 > 解决方案 > 在 Redux 中间件中是否应该总是最后调用“下一个”?

问题描述

tl;dr:在 Redux 中间件函数中,是否可以在调用next完成更新存储后调度新操作?

我正在使用Flutterbuilt-flutter-redux构建一个 HackerNews 阅读器,基于 Brian Egan 的TodoMVC 示例。它使用 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)

在调用之后在 Redux 中间件中调度新动作是不是很酷next,或者这是某种反模式?如果它一种反模式,那么实现此流程的最佳方式是什么?

标签: reduxflutter

解决方案


是的,这很好——当一个动作被调度时,一个中间件可以做任何它想做的事情这包括修改/记录/延迟/交换/忽略原始操作,以及调度其他操作。


推荐阅读