如何在 RxJS mergeMap 中包含条件和非条件调用?
How do you include conditional and non-conditional calls in an RxJS mergeMap?
在 api 调用获取数据后,我需要在 FETCH_DATA_SUCCESS
上调用一些进一步的操作。
必须在每个 'FETCH_DATA_SUCCESS'
上调用 'RESET_IMAGE_DATA'
和 'INITIALISE_FILTERS'
操作。但是,只有在 action.context === 'pivot'
.
时才必须调用 'SET_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',
}
)}
)
);
试试这个:
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.: 如果你不喜欢这种语法,你可以使用数组并根据条件推送它,然后 return 它与 of(...actions)
您可以将 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'
}
]);
})
);
在 api 调用获取数据后,我需要在 FETCH_DATA_SUCCESS
上调用一些进一步的操作。
必须在每个 'FETCH_DATA_SUCCESS'
上调用 'RESET_IMAGE_DATA'
和 'INITIALISE_FILTERS'
操作。但是,只有在 action.context === 'pivot'
.
'SET_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',
}
)}
)
);
试试这个:
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.: 如果你不喜欢这种语法,你可以使用数组并根据条件推送它,然后 return 它与 of(...actions)
您可以将 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'
}
]);
})
);