如何在回调中在 redux-saga 中“屈服”?

新手上路,请多包涵

因为在回调中不允许使用“yield”语句,我如何在回调中使用 redux-saga 的“put”功能?

我想要以下回调:

 function onDownloadFileProgress(progress) {
  yield put({type: ACTIONS.S_PROGRESS, progress})
}

这不起作用并以“意外标记”结束,因为在普通函数中不允许 yield 。否则我不能将回调作为“ 函数 * ”传递,这将允许收益。 ES6 似乎在这里坏掉了。

我读过 redux-saga 提供了一些称为“ 通道”的功能,但老实说,我不明白。我已经多次阅读有关这些渠道和示例代码的内容,但在所有示例中,它们都解决了非常困难和不同的问题,而不是我的简单案例,最终我已经到了那里。

有人可以告诉我如何处理这个问题的解决方案吗?

整个上下文:

 function onDownloadFileProgress(progress) {
  yield put({type: ACTIONS.S_PROGRESS, progress})
}

export function * loadFile(id) {
  let url = `media/files/${id}`;

  const tempFilename = RNFS.CachesDirectoryPath + '/' + id;

  const download = RNFS.downloadFile( {
    fromUrl: url,
    toFile: tempFilename,
    background: false,
    progressDivider: 10,
    progress: onDownloadFileProgress,
  })

  yield download.promise;

}

原文由 delete 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 434
2 个回答

正如您已经提到的,一种可能的解决方案是使用 channels 。这是一个适用于您的情况的示例:

 import { channel } from 'redux-saga'
import { put, take } from 'redux-saga/effects'

const downloadFileChannel = channel()

export function* loadFile(id) {
  ...
  const download = RNFS.downloadFile({
     ...
     // push `S_PROGRESS` action into channel on each progress event
     progress: (progress) => downloadFileChannel.put({
       type: ACTIONS.S_PROGRESS,
       progress,
     }),
  })
  ...
}

export function* watchDownloadFileChannel() {
  while (true) {
    const action = yield take(downloadFileChannel)
    yield put(action)
  }
}

这里的想法是,我们将为从 RNFS.downloadFile 发出的每个进度事件在通道上推送一个 S_PROGRESS 操作。

我们还必须启动另一个 saga 函数,它在 while 循环( watchDownloadFileChannel )中监听每个推送的动作。每次从频道采取行动时,我们使用正常的 yield put 告诉 redux-saga 应该调度这个行动。

我希望这个答案能帮助你。

原文由 Alex 发布,翻译遵循 CC BY-SA 3.0 许可协议

这是最简单的方法:

 import store from './store' // import redux store
store.dispatch(your action creator here)

原文由 Umbrella 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题