可观察到的Redux:操作完成后组件如何订阅以做出反应?

时间:2020-09-25 08:58:00

标签: reactjs redux rxjs redux-observable

假设此演示代码:

const pingEpic = action$ => action$.pipe(
  filter(action => action.type === 'PING'),
  delay(1000), // Asynchronously wait 1000ms then continue
  mapTo({ type: 'PONG' })
);

// later...
dispatch({ type: 'PING' });

const pingReducer = (state = {}, action) => {
  switch (action.type) {
    case 'PING':
      return state;

    case 'PONG':
      return state;

    default:
      return state;
  }
};

在一个特定的组件中,该组件与分派PING或PONG都不使用任何Redux状态无关,我想以某种方式订阅操作生命周期以及PONG操作何时完成(即由reducer处理) ),它将执行一个回调。像这样:

const myComponent = () => {
  ofActionSuccessful('PONG').subscribe( () => console.log('PONG has just completed'));
}

类似https://www.ngxs.io/advanced/action-handlers

我该如何实现?

我不想在化简器中链接某些逻辑,因为它与该组件严格相关,与存储无关。

1 个答案:

答案 0 :(得分:1)

来自redux-observable docs

在化简器已经收到它们之后,史诗与正常的Redux分发通道并排运行-因此您不能“吞咽”进来的动作。动作始终会在您的Epics接收到它们之前通过您的化简器进行。

因此我们可以使用史诗获得“ PONG”信号。

const allActions$ = new Subject();

// This must be merged into your root epic.
export const tapAllActions = (action$) =>
  action$.pipe(tap(allActions$), concatMapTo(EMPTY));

export const ofActionSuccessful = (actionType) =>
  allActions$.pipe(filter(({ type }) => type === actionType));