Tom*_*mer 3 reactjs redux redux-saga
我正在使用redux-saga来上传文件,我试图找到一种方法来在上传进度发生变化时调度事件:
const data = new FormData();
data.append('file', fileWrapper.file);
const uploadedFile = yield call(request, requestURL, {
method: 'POST',
headers: {
'X-Requested-With': 'XMLHttpRequest'
},
body: data
});
Run Code Online (Sandbox Code Playgroud)
知道如何附加上传进度事件吗?
首先,答案取决于你如何进行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 })
}
Run Code Online (Sandbox Code Playgroud)
资料来源:https://github.com/redux-saga/redux-saga/issues/613#issuecomment-258384017
PS在我个人看来,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});
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3604 次 |
| 最近记录: |