【问题标题】:Redux-observable: how a component can subscribe to react when action is completed?Redux-observable:当动作完成时组件如何订阅响应?
【发布时间】:2021-01-11 14:29:45
【问题描述】:

假设这个演示代码:

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 操作何时完成(即已被减速器处理) 它执行一个回调。比如:

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

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

我怎样才能做到这一点?

我不想在reducer中链接一些逻辑,因为它是与那个组件严格相关的东西,与store无关。

【问题讨论】:

    标签: reactjs redux rxjs redux-observable


    【解决方案1】:

    来自redux-observable docs

    在 reducer 已经接收到 Epic 之后,Epic 与正常的 Redux 调度通道一起运行——因此你不能“吞下”传入的操作。动作总是在您的 Epic 收到它们之前通过您的减速器。

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

    【讨论】:

      猜你喜欢
      • 2020-08-11
      • 1970-01-01
      • 2018-09-05
      • 2021-11-16
      • 1970-01-01
      • 1970-01-01
      • 2019-08-21
      • 2020-12-29
      • 1970-01-01
      相关资源
      最近更新 更多