首先,答案取决于你如何做uploadRequest。
您似乎正在使用window.fetch API。此 API 不为您提供接收上传进度事件的方法。
因此,您需要切换到使用 XMLHttpRequest 或以方便的方式包装它的库。我建议您查看axios 和superagent。它们都提供了一种监听进度事件的方法。
下一个主题是如何在redux-saga 中调度进度操作。您需要使用fork 创建一个分叉的异步任务并在那里调度操作。
function uploadEmitter(action) {
return eventChannel(emit => {
superagent
.post('/api/file')
.send(action.data)
.on('progress', function(e) {
emit(e);
});
});
}
function* progressListener(chan) {
while (true) {
const data = yield take(chan)
yield put({ type: 'PROGRESS', payload: data })
}
}
function* uploadSaga(action) {
const emitter = uploadEmitter()
yield fork(progressListener, emitter)
const result = yield call(identity(promise))
yield put({ type: 'SUCCESS', payload: result })
}
来源:https://github.com/redux-saga/redux-saga/issues/613#issuecomment-258384017
P.S.在我个人看来,redux-saga 不是实现此类功能的合适工具。使用redux-thunk 这样做会更干净:
function uploadAction(file) {
return dispatch => {
superagent
.post('/api/file')
.send(action.data)
.on('progress', function(event) {
dispatch({type: 'UPLOAD_PROGRESS', event});
})
.end(function(res) {
if(res.ok) {
dispatch({type: 'UPLOAD_SUCCESS', res});
} else {
dispatch({type: 'UPLOAD_FAILURE', res});
}
});
}
}