2016-03-15 57 views
0

如何處理和承諾進度?Redux和承諾進度

我想在promise執行時顯示一些旋轉杆或其他東西,我使用axios來處理請求,但他們有一個API來處理在請求的配置對象中這樣的進程:

{ 
    progress: function(progressEvent) { 
     // Do whatever you want with the native progress event 
    } 
} 

但我只能發送一個終極版動作要求,如:

return { 
    type: "HTTP_REQUEST", 
    payload: axios.get("/webAPI/data", configObj) 
} 

我如何處理與這些條件的進展情況?

回答

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

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,就像你已經發起一個請求(也可能一個兩個成功的和不成功的結果)的動作與另一動作。