簡體   English   中英

收聽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已成功調度時,可以在其中執行操作。 這可能類似於關閉模態,或者調度另一個動作。

我在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));
    }
  };

原來, redux-thunk支持返回promise,所以我可以只返回promise,而不必使用回調方法。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM