简体   繁体   English

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

[英]How do I use yield inside a callback on redux-saga?

I have a callback which I need to return true or false to trigger some external action, I need to make an API call inside this callback, so I need to get the state and dispatch some actions inside the callback, I don't know if I can use eventChannel because this callback could not be a generator, only a plain function.我有一个回调,我需要返回 true 或 false 来触发一些外部动作,我需要在这个回调中进行 API 调用,所以我需要在回调中获取状态并调度一些动作,我不知道是否我可以使用 eventChannel 因为这个回调不能是一个生成器,只能是一个普通的函数。 I need to do something like this.我需要做这样的事情。

  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;
  });

Btw, this is zendesk API.顺便说一句,这是zendesk API。

Your not going to be able to pass a generator function to that API.您将无法将生成器函数传递给该 API。 The work around is to dispatch an action directly to the redux store and then write a saga that listens for that action.解决方法是直接将操作分派到 redux 存储,然后编写一个侦听该操作的 saga。

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

You will have to make the redux store exportable from where you create it.您必须使 redux 存储可从创建它的位置导出。 So that you can directly access it here.这样你就可以在这里直接访问它。

One of the challenges is how to yield in the callback.挑战之一是如何在回调中yield How about importing dispatch ?导入dispatch怎么样? Isn't dispatch the non-generator version of yield ?不是 dispatch 非生成器版本的yield吗?

Should you be using React, doing so seems to be an option.如果您使用 React,这样做似乎是一种选择。

In the same saga that you use to specify the callback, you can subsequently listen for the action created in the dispatch/action creator callback.在用于指定回调的同一个 saga 中,您可以随后侦听在 dispatch/action creator 回调中创建的操作。 That's done by specifying another watchFor function (in my setup, any number of exported watchFor functions get added to the pool of saga watchers).这是通过指定另一个watchFor函数来完成的(在我的设置中,任意数量的导出watchFor函数都被添加到 saga 观察者池中)。

The paired saga worker can finalize whatever needs to happen to the data returned from the API call before using your final action creator to "document" the workflow by updating the store.配对的 saga worker可以在使用最终操作创建者通过更新存储来“记录”工作流程之前,最终确定从 API 调用返回的数据需要发生的任何事情。

The other option might be to wrap the api call in an eventChannel (see: https://github.com/redux-saga/redux-saga/issues/1178 ).另一种选择可能是将 api 调用包装在eventChannel (请参阅: https : //github.com/redux-saga/redux-saga/issues/1178 )。

- E - E

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM