我在 React & Redux 项目中使用 Redux-Observable Epic。我有多个 Action 需要发出,本来这就是我一直在做的,
1) 捕捉史诗中的 START_ACTION
2) 获取远程数据
3)返回一个新的Observanble
例如:
import fetch from 'isomorphic-fetch';
import {Observable} from 'rxjs/Observable';
import {switchMap} from 'rxjs/operator/switchMap';
import {mergeMap} from 'rxjs/operator/mergeMap';
const fetchAsync = (arg) => {
// return an observable of promise
return Observable::from(fetch(url + arg));
}
export function myEpic = (action$) => {
action$.ofType(START_ACTION)
::switchMap(action => {
return fetchAsync('/action.payload')
::mergeMap(result => {
return Observable::of({type: ACTION_COMPLETE, payload: result})
})
})
};
现在,如果我需要在 START_ACTION
之后、ACTION_COMPLETE
之前发出另一个操作 SECOND_ACTION
该怎么办?换句话说,在不确保 SECOND_ACTION
命中 reducer 的情况下,不应发出 ACTION_COMPLETE
。
我可以编写另一个单独的 Epic 函数来执行此操作,但是还有其他更简单的方法吗?
最佳答案
To simplify the question, I just want to emit the SECOND_ACTION before the async.
要在执行fetchAsync
之前发出另一个操作,您可以使用Observable.concat
或startWith
运算符,这基本上是糖连接。
export function myEpic = (action$) => {
action$.ofType(START_ACTION)
::switchMap(action => {
return fetchAsync('/action.payload')
::map(result => ({ type: ACTION_COMPLETE, payload: result })
::startWith({ type: SECOND_ACTION })
})
};
由于 SECOND_ACTION
同步跟随 START_ACTION
,因此请记住,通常您应该让您的 reducer 监听 START_ACTION
,而不是发出另一个操作。多个 reducer 从同一个操作转换状态是正常的,也是 redux 的主要好处之一。
也就是说,在某些时候,关注点分离确实更为理想,因此这只是一个一般性提示。
<小时/>上一个答案
如果您想按顺序发出两个操作,您可以将附加操作作为参数传递给 Observable.of(...actions)
,因为它接受任意数量的参数并按顺序发出它们。
export function myEpic = (action$) => {
action$.ofType(START_ACTION)
::switchMap(action => {
return fetchAsync('/action.payload')
::mergeMap(result => {
return Observable::of(
{ type: SECOND_ACTION },
{ type: ACTION_COMPLETE, payload: result }
)
})
})
};
如果这不是您的意思,我深表歉意。问题没说清楚。
关于javascript - Redux-Observable 中具有依赖关系的多个操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48756832/