如何在回调中"减少收益率"?

del*_*ete 17 javascript yield ecmascript-6 redux redux-saga

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

我想要进行以下回调:

function onDownloadFileProgress(progress) {
  yield put({type: ACTIONS.S_PROGRESS, progress})
}
Run Code Online (Sandbox Code Playgroud)

这不起作用并以"意外令牌"结束,因为普通函数不允许产生.否则我不能将回调作为" 函数* " 传递,这将允许收益.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;

}
Run Code Online (Sandbox Code Playgroud)

Ale*_*lex 28

正如您已经提到的,一种可能的解决方案是使用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)
  }
}
Run Code Online (Sandbox Code Playgroud)

这里的想法是,我们将S_PROGRESS针对从中发出的每个进度事件在通道上执行操作RNFS.downloadFile.

我们还必须启动另一个saga函数,它在while循环(watchDownloadFileChannel)中监听每个被推送的动作.每次从通道获取操作时,我们使用法线yield put来告知redux-saga应该调度此操作.

我希望这个答案会对你有所帮助.

  • 好的,对于谁想知道如何连接“watchDownloadChannel”。您可以简单地导出此代码“takeEvery(channel, watchDownloadChannel)”并将其导入到“rootSaga”中 (4认同)
  • 这似乎是我的类似问题的解决方案,但我得到通道缓冲区溢出.你是如何将`watchDownloadFileChannel`连接到sagaMiddleware的? (3认同)