【问题标题】:Redux and promise progressRedux 和承诺进度
【发布时间】:2016-03-15 12:45:17
【问题描述】:

如何处理和承诺 redux 的进展?

我想在 Promise 执行时显示一些旋转条或其他东西,我正在使用 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)
}

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

【问题讨论】:

    标签: javascript redux redux-thunk


    【解决方案1】:

    虽然 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 的操作,就像您已经有一个用于发起请求的操作(可能同时用于成功和不成功结果的操作)。

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-09-15
        • 2017-01-05
        • 2018-01-08
        • 1970-01-01
        • 2016-10-03
        • 1970-01-01
        • 2014-11-21
        • 1970-01-01
        相关资源
        最近更新 更多