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

我怎样才能做到这一点?

我不想链接reducer中的一些逻辑,因为它与该组件严格相关,与存储无关。

从redux可观察文档:

Epic与正常的Redux调度通道一起运行,在减速器已经收到它们之后——所以你不能"燕子;即将到来的动作。在你的史诗收到减速器之前,动作总是在减速器中运行。

所以我们可以使用史诗来获得;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));

最新更新