我如何处理并承诺在redux中取得进展?
我希望在承诺执行时显示一些旋转条或其他内容,我使用axios来处理请求,但是他们有一个api来处理配置中的这样的进度请求的对象:
{
progress: function(progressEvent) {
// Do whatever you want with the native progress event
}
}
但我只能通过redux动作发送请求,例如:
return {
type: "HTTP_REQUEST",
payload: axios.get("/webAPI/data", configObj)
}
如何处理具有这些条件的进度事件?
答案 0 :(得分:2)
虽然gabdallah的答案是正确的,但我觉得它只能部分回答这个问题。如果您愿意,可以轻松地将两个答案中的代码组合在一起。
如果您执行想要向用户显示进度,您可以从进度回调中调度特定的进度操作,并将当前进度作为有效负载。像这样:
{
progress: function(progressEvent) {
return dispatch({
type: "HTTP_REQUEST_PROGRESS",
payload: {
url: "/webAPI/data",
currentBytes: progressEvent.current,
totalBytes: progressEvent.total // properties on progressEvent made up by yours truly
}
});
}
}
从本质上讲,你只需要另一个代表request progress
的动作,就像你已经有一个动作来发起一个请求(可能是一个成功和不成功的结果)。
答案 1 :(得分:0)
如果您正在查看只显示微调器而不是进度条,那么您实际上不需要进度功能。相反,我会建议这些内容:
const axiosAction = function(configObj) {
// We have to thunk the dispatch since this is async - need to use the thunk middleware for this type of construct
return dispatch => {
/* action to notify the spinner to start (ie, update your store to have a
loading property set to true that will presentationally start the spinner) */
dispatch({
type: 'AXIOS_REQUEST_STARTING'
});
return axios.get("/webAPI/data", configObj)
.then(res => {
/* action to set loading to false to stop the spinner, and do something with the res */
return dispatch({
type: 'AXIOS_REQUEST_FINISHED',
payload: res,
})
})
.catch(err => /* some error handling*/);
};
}
已修改为redux-thunk
添加链接