處理非同步 fucntion 如各種 API
- 寫一個MIDDLEWARE 處理非同步function
- 處理非同步function
- 根據 STATE 改變 VIEW 值
非同步function需等待API回傳,故MIDDLEWARE需能等回傳後再次讓 DISPATCHER 接著做事
const thunk = store => next => action => {
if(typeof action === 'function'){
action(store.dispatch, store.getState());
}else{
next(action);
}
}
var asyncIncrease = (dispatch, state) => {
dispatch({type:"INCREMENT_LOADING"});
_fakeServerApi.increaseCount(state.count.result,
data => dispatch({ type: 'INCREMENT' }));
}
var _fakeServerApi = {
// imitate the server API
increaseCount : ( currentCount, cb ) =>
setTimeout(()=> cb(currentCount + 1), 5000)
}
var getRandomImages = (dispatch, state) => {
dispatch({ type: 'IMAGES_LOADING' });
var imgurAPI = "https://api.imgur.com/3/gallery/random/random/1";
$.getJSON(imgurAPI).done(data => dispatch({ type: 'IMAGES', data:data.data}))
}
定義要在VIEW顯示的值為變數status,待API回傳後讓STATE更新stauts
if(state.count.loading){
$('
---
#status').text("is loading...");
}else{
$('
---
#status').text("loaded");
}
- 好好利用,讓debug之路順暢
- 好好利用,讓VIEW聽話
- 好好利用,讓UX提升
