首页 > 解决方案 > 从 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.

标签: reduxrxjsredux-observable

解决方案


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' },
)),

推荐阅读