"next"是否应该始终在 Redux 中间件中最后调用?



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

我正在使用Flutter和build-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很酷,还是某种反模式?如果是反模式,实现此流的最佳方法是什么?

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

最新更新