从 redux-observable 中调度多个动作

Dispatch multiple actions from in 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 只是将一项映射到另一项,因此当您 return [action1, action2] 您仍然在 return 数组并且 redux-observable 尝试处理它本身就是一个动作。您想要的是 "unwrapping" 数组(或使用 concat 创建的 Observable)returned.

因此,您可以使用 mergeMap(或 concatMap)而不是使用 map,当您 return 一个数组时,它会迭代它并为每一项:

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