如何在redux-saga的回调函数中使用yield?

3

我有一个回调函数,在其中需要返回true或false以触发一些外部操作,我需要在这个回调函数中进行API调用,因此我需要获取状态并在回调函数内分发某些操作,但我不知道是否可以使用eventChannel,因为这个回调函数可能不是一个生成器函数,而只是一个普通的函数。我需要像这样做。

  zafClient.on('ticket.save', () => {
      const state = yield select();
      yield put(actionWithApiCall())

      // I need to wait for the action to finish and then return something 
      // based on the response from the API
      // I know how to block the saga to wait for the action dispatched 
      // the problem is that I can't use yield here

      return somethingfromthestore;
  });

顺便提一下,这是Zendesk API。

2个回答

1

你无法将生成器函数传递给该API。解决方法是直接向redux存储器分派一个操作,然后编写一个侦听该操作的saga。

zafClient.on('ticket.save', () => reduxStore.dispatch(actionWithApiCall()))

你需要使redux store可以从创建它的位置导出,这样你就可以直接在此处访问它。

那么我应该如何等待 API 响应被存储,以便根据更新后的存储返回内容呢? - Khantus
使用 yield take(MY_API_ACTION) 然后 yield select() 在新的 Saga 中从 store 获取数据。 - David Bradshaw

0

其中一个挑战是如何在回调中使用 yield。那么,导入 dispatch 怎么样?难道 dispatch 不就是 yield 的非生成器版本吗?

如果你正在使用 React,这似乎是一个选项。

在同一个 saga 中,您可以使用另一个 watchFor 函数(在我的设置中,任意数量的导出的 watchFor 函数都会添加到 saga watcher 池中)来监听在 dispatch/action creator 回调中创建的 action。

配对的 saga worker 可以在使用最终 action creator 更新存储以“记录”工作流之前,完成对从 API 调用返回的数据所需的任何操作。

另一种选择可能是将 api 调用包装在一个 eventChannel 中(参见:https://github.com/redux-saga/redux-saga/issues/1178)。

- E


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接