【问题标题】:How do you include conditional and non-conditional calls in an RxJS mergeMap?如何在 RxJS 的 mergeMap 中包含条件调用和非条件调用?
【发布时间】:2019-01-17 17:17:43
【问题描述】:

在 api 调用获取数据后,我需要在 FETCH_DATA_SUCCESS 上调用一些进一步的操作。

'RESET_IMAGE_DATA''INITIALISE_FILTERS' 操作必须在每个 'FETCH_DATA_SUCCESS' 上调用。但是,'SET_PIVOT' 只能在 action.context === 'pivot' 时调用。

所以,有两种可能的情况。

在第一种情况下,'RESET_IMAGE_DATA''INITIALISE_FILTERS' 被调用。

在第二种情况下,'RESET_IMAGE_DATA''INITIALISE_FILTERS''SET_PIVOT' 被调用。

我尝试了各种解决方案都没有成功,我最近的尝试如下。任何帮助将不胜感激。

const loadDataEpic = (action$, state$) =>
  action$.pipe(
    ofType('FETCH_DATA_SUCCESS'),
    mergeMap(action => {
      if (action.context === 'pivot') {
        return of({
          type: 'SET_PIVOT',
        });
      }
      return of(
        {
          type: 'RESET_IMAGE_DATA',
        },
        {
          type: 'INITIALISE_FILTERS',
        }
      )}
    )
  );

【问题讨论】:

  • 我认为没有什么问题。也许你可以用一个三元运算符来缩短它。
  • 我已更新问题以使其更清晰

标签: javascript rxjs redux-observable


【解决方案1】:

您可以将of 更改为from,以便发送一个数组,因为数组允许轻松动态插入。

像这样:

const loadDataEpic = (action$, state$) =>
    action$.pipe(
        ofType('FETCH_DATA_SUCCESS'),
        mergeMap(action => {
            const pivotActions = action.context === 'pivot'
                ? [{ type: 'SET_PIVOT' }]
                : [];
            return from([
                ...pivotActions,
                {
                    type: 'RESET_IMAGE_DATA'
                },
                {
                    type: 'INITIALISE_FILTERS'
                }
            ]);
        })
    );

【讨论】:

  • 干杯,正是我要找的东西
【解决方案2】:

试试这个:

const loadDataEpic = (action$, state$) =>
  action$.pipe(
    ofType('FETCH_DATA_SUCCESS'),
    mergeMap(action => {
     const isPivot = action.context === 'pivot';
     return of(
       { type: 'RESET_IMAGE_DATA' },
       { type: 'INITIALISE_FILTERS' },
       ...(isPivot ? [{ type: 'SET_PIVOT' }] : [])
     );
    })
  );

如果条件为真,它只会添加动作SET_PIVOT

p.s.:如果你不喜欢这个语法,你可以使用一个数组并根据条件推送它,然后用of(...actions)返回它

【讨论】:

    猜你喜欢
    • 2021-01-04
    • 1970-01-01
    • 2018-07-25
    • 2022-12-07
    • 2012-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    相关资源
    最近更新 更多