监听 Redux 中的调度动作

Listen for dispatched action in Redux

我想知道是否有办法监听已在 redux 中成功发送的操作?

在 Angular 的 ngxs 状态管理库中,我可以执行以下操作:

ngOnInit() {
  this.actions$
    .pipe(
      ofActionSuccessful(AddedThingToDo),
      map((event: AddedThingToDo) => event.thingToDo),
      tap(thingToDo => console.log('Action was successfully dispatched'))
    )
   .subscribe();
}

当我知道 AddedThingToDo 已成功发送时,我可以在哪里执行操作。这可能类似于关闭模式,或者可能调度另一个操作。

我将 ng-redux 用于 Angular 1.x,但我认为原则应该与 React redux 相同。

我绕过它的唯一方法是在我的操作中使用回调,但感觉很不对:

export const addThingToDo = (model: IThingToDo, onSuccess?: (model: IThingToDo) => void) =>
  async (dispatch: Dispatch) => {
    dispatch(addingThingToDo());
    try {
      const createdItem = await api.post<IThingToDo>(url, model);
      dispatch(addedThingToDo(createdItem));
      if (onSuccess) {
        onSuccess(createdItem);
      }
    }
    catch (ex) {
      dispatch(addThingToDoFailure(ex));
    }
  };

原来 redux-thunk 支持 returning 承诺,所以我可以 return 承诺而不是使用回调方法。

export const addThingToDo = (model: IThingToDo) =>
  async (dispatch: Dispatch): Promise<IThingToDo> =>
    await new Promise<IThingToDo>(async (resolve, reject) => {
      dispatch(addingThingToDo());
      try {
        const newItem = await api.post<IThingToDo>(url, model);
        dispatch(addedThingToDo(newItem));
        resolve(newItem);
      } catch (ex) {
        dispatch(addThingToDoFailure(ex));
        reject(ex);
      }
    });


this.addThingToDo(thingToDo)
  .then(t => navigateTo(`/things-to-do/${t.id}`));