redux - 在 Redux 中间件中是否应该总是最后调用“下一个”?
问题描述
tl;dr:在 Redux 中间件函数中,是否可以在调用next
完成更新存储后调度新操作?
我正在使用Flutter和built-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
,或者这是某种反模式?如果它是一种反模式,那么实现此流程的最佳方式是什么?
解决方案
是的,这很好——当一个动作被调度时,一个中间件可以做任何它想做的事情。这包括修改/记录/延迟/交换/忽略原始操作,以及调度其他操作。
推荐阅读
- javascript - Socket.io disconnected unexpectedly
- c++ - clang 如何使用 SourceLocation 来跟踪标识符的文件名、行和列信息?
- python - 我在哪里将 geckodriver.exe 放在网络主机上
- reporting-services - 我没有在报表生成器中从 IF-Then-Else 跳转到 IIF
- php - 如何用图片链接替换php中的图片?
- python-3.x - keyError in pandas on selecting multiple columns
- php - 无法打开输入文件:创建命令/运行它时 codenvy 中的工匠错误
- vb.net - Listview 使用自定义颜色突出显示所选项目 vb.net
- reactjs - Submitting form with redux form
- c# - 使用 string.Remove() 从字符串中删除特定字符的所有并发