假设我有一个搜索组件,可以根据用户选择的标签进行搜索(Think Pocket)。如果用户取消选择所有标签,我知道搜索的结果将为空;没有必要打服务器。我怎样才能重构这部史诗以有条件地运行副作用?
const removeTagEpic = (action$: any, store: any) =>
action$
.ofType(types.REMOVE_SELECTED_TAG)
.map((action: any) => action.payload)
.mergeMap((tag: any) => {
//only do this is store.getState().tags > 0
ajax.getJSON(`https://api.github.com/users/dwaynelavon`)
.flatMap(response =>
Observable.concat(
Observable.of(actions.fetchingProfiles(true)),
Observable.of(actions.fetchProfilesFulfilled(profiles)),
Observable.of(actions.fetchingProfiles(false))
)
)
})
答案 0 :(得分:1)
您是否无法使用filter
运算符并检查其中的标记?
const removeTagEpic = (action$: any, store: any) =>
action$
.ofType(types.REMOVE_SELECTED_TAG)
.filter(_ => store.getState().tags > 0)
.map((action: any) => action.payload)
.mergeMap((tag: any) => {
ajax.getJSON(`https://api.github.com/users/dwaynelavon`)
.flatMap(response =>
Observable.concat(
Observable.of(actions.fetchingProfiles(true)),
Observable.of(actions.fetchProfilesFulfilled(profiles)),
Observable.of(actions.fetchingProfiles(false))
)
)
})
如果不满足条件,则types.REMOVE_SELECTED_TAG
的来源不会被发出。