简体   繁体   English

收听Redux中已调度的动作

[英]Listen for dispatched action in Redux

I'm wondering if there's a way to listen for an action that's been successfully dispatched in redux? 我想知道是否有办法监听在redux中成功调度的操作?

In the ngxs state management library for Angular, I can do the following: 在Angular的ngxs状态管理库中,我可以执行以下操作:

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

Where I can then perform an action when I know that AddedThingToDo has been successfully dispatched. 当我知道AddedThingToDo已成功调度时,可以在其中执行操作。 This could be something like closing a modal, or perhaps dispatching another action. 这可能类似于关闭模态,或者调度另一个动作。

I'm using ng-redux for Angular 1.x, however I think the principle should remain the same that it would for react redux. 我在Angular 1.x中使用ng-redux ,但是我认为原理应与对React Redux的使用相同。

The only way I've been getting around it is with a callback in my actions, but it feels very wrong: 我一直在解决它的唯一方法是在我的操作中使用回调,但是感觉很不对劲:

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

Turns out redux-thunk supports returning promises, so I can just return a promise rather than use a callback method. 原来, 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