收听Redux中已调度的动作

时间:2018-11-15 16:43:27

标签: javascript redux ngredux

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

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

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

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

我在Angular 1.x中使用ng-redux,但是我认为该原理应与对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));
    }
  };

1 个答案:

答案 0 :(得分:0)

结果证明redux-thunk支持返回承诺,因此我可以返回承诺而不是使用回调方法。

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}`));