redux - 从 redux-observable 中调度多个动作
问题描述
我正在尝试向 redux 发送多个操作。这是我的代码
action$.pipe(
ofType(trigger),
mergeMap(({ payload }) =>
from(endpoint(payload)).pipe(
map(response =>
// this works fine
// setData(response.data)
// this doesn't
concat(
of(setData(response.data)),
of({ type: 'hello' })
)
// I also tried
[
of(setData(response.data)),
of({ type: 'hello' })
]
)
)
),
catchError(err => Promise.resolve(creators.setError(err)))
)
单次调度有效,但如果我尝试上述多个项目,我会得到Uncaught Error: Actions must be plain objects. Use custom middleware for async actions.
解决方案
map
只需将一个项目映射到另一个项目,因此当您返回时,[action1, action2]
您仍然会返回一个数组并redux-observable
尝试将其视为一个动作本身。相反,您想要的是“解包”concat
返回的数组(或创建的 Observable)。
因此,map
您可以使用mergeMap
(or concatMap
) 而不是使用,当您返回一个数组时,它将对其进行迭代并为每个项目单独排放:
mergeMap(response => [
setData(response.data),
{ type: 'hello' },
]),
如果这看起来太奇怪了,您可以将数组包装起来from
以使其更明显:
mergeMap(response => from([
setData(response.data),
{ type: 'hello' },
])),
你甚至可以使用一个of
:
mergeMap(response => of(
setData(response.data),
{ type: 'hello' },
)),
推荐阅读
- modal-dialog - Laravel 8 使用模态更新数据
- tensorflow - 多元 GMM TensorFlow 实现
- reactjs - 单击按钮时页面未滚动到顶部
- flutter - 如何在 Flutter 中自定义 file_picker UI
- node.js - 有模块问题 Dockerizng 简单节点应用程序
- java - 输出是23。请解释
- android - QT Android Gstreamer RTMP流管道绿线故障
- npm - npm install 给出 '.' 不被识别为内部或外部命令、可运行程序或批处理文件。错误
- flutter - Flutter 从小部件外部更改 PageView 页面
- python-multiprocessing - 通过 Mac 终端访问 Python 共享内存