gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 06:47:46 24 4
gpt4 key购买 nike

tl;dr:在 Redux 中间件函数中,是否可以在调用 next 完成商店更新后分派(dispatch)新操作?

我正在使用 Flutter 构建一个 HackerNews 阅读器和 built-flutter-redux , 基于 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 列表更新我的应用程序的状态。

在某些时候我需要分派(dispatch)另一个操作,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 中间件中分派(dispatch)新 Action 是不是很酷,或者这是某种反模式?如果它一个反模式,那么实现这个流程的最佳方式是什么?

最佳答案

是的,这很好 - 中间件可以在分派(dispatch)操作时字面上做任何它想做的事情。这包括修改/记录/延迟/交换/忽略原始操作,以及分派(dispatch)其他操作。

关于redux - "next"应该总是在 Redux 中间件中最后调用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50353571/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com