重新开始并承诺取得进展

Redux and promise progress

本文关键字:承诺 重新开始      更新时间:2023-09-26

我如何处理并承诺在 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)
}

如何在这些条件下处理进度事件?

虽然加卜达拉的回答是正确的,但我觉得它只是部分回答了这个问题。如果您愿意,可以轻松组合两个答案中的代码。

如果确实要向用户显示进度,可以从进度回调中调度特定的进度操作,并将当前进度作为有效负载。像这样:

{  
   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的操作,就像您已经有一个用于启动请求的操作(并且可能是一个成功和不成功结果的操作)。

如果您只显示微调器而不是进度条,那么您真的不需要进度函数。相反,我会推荐一些类似的东西:

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 的链接