我是 RxJS 的入门级开发人员, 我用 react , 还原, react 还原, redux-可观察的, 最重要的是在我的业余项目中;
但我不明白,为什么我的史诗代码块不能按我想要的方式工作,希望有人帮助我。
/* store actions */
export const ACTION_1 = 'ACTION_1';
export const ACTION_2 = 'ACTION_2';
export const ACTION_3 = 'ACTION_3';
/* store reducer */
import * as actionTypes from 'actions.js';
const someInitialState = {};
const reducer = (state = someInitialState , action) => {
switch(actionTypes.ACTION_1){
case(actionTypes.ACTION_1):{
return {
...state,
/*do something...*/
}
}
case(actionTypes.ACTION_2):{
/*do something...*/
}
case(actionTypes.ACTION_3):{
/*do something...*/
}
}
}
/* actionEpic.js */
import * as actionTypes from 'actions.js'
const actionEpic = (action$ , store$) => {
retrun action$.pipe(
ofType(actionTypes.ACTION_1),
map( () => ({type : actionTypes.ACTION_2}) ),
map( () => ({type : actionTypes.ACTION_3}) ),
)
}
这是伪代码,因此请忽略详细的语法和结构。
我的问题是为什么在我的actionEpic史诗中, 第一个 Action 1 和最后一个 Action 3 将被发出并且工作正常, 但中间的 Action 2 总是被忽略,从不发出。
如果我想一个接一个地发出这3个 Action ,该怎么做?
有人可以帮助我吗 对我的帖子周围的英语语法问题感到抱歉, 非常感谢。
最佳答案
您可以使用展平运算符(例如 mergeMap
)发出这两个操作,因此您的代码将类似于:
const { of } = rxjs; // = require("rxjs")
const { filter, mergeMap } = rxjs.operators; // = require("rxjs/operators")
const actionEpic = (actions$) => {
return actions$.pipe(
filter(a => a.type === "ACTION_1"),
mergeMap(() => [
{ type: "ACTION_2" },
{ type: "ACTION_3" }
])
)
}
const actions$ = of({ type: "ACTION_1" });
actionEpic(actions$).subscribe(e => console.log(e));
<script src="https://unpkg.com/rxjs@6.5.3/bundles/rxjs.umd.min.js"></script>
关于reactjs - 如何在每个 Action 中发出事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58469959/