一、redux基礎
redux
react-redux
二、redux處理異步的中間件
redux-thunk
redux-saga
三、redux-request-async-middleware
先從redux文檔中的異步action說起,每個接口調用需要dispatch三個同步action,分別是:
也就是一個接口發(fā)起是這樣的
dispatch(fetchPostsRequest(subject));fetch(url).then(res => { dispatch(fetchPostsSuccess(subject, res));}).catch(e => { dispatch(fetchPostsFailure(subject, e));})而我做的事情只是將這個操作封裝進中間件里,特殊的地方在于:
中間件源碼
export const reduxRequest = store => next => action => { let result = next(action); let { type, subject, model } = action; let _next = action.next; if(type === FETCH_POSTS_REQUEST) { model().then(response => { _next && _next(response); store.dispatch(fetchPostsSuccess(subject, response)); }).catch(error => { console.error(error); store.dispatch(fetchPostsFailure(subject, error)); }); } return result};reducer源碼
export const requests = (state = {}, action) => { switch (action.type) { case FETCH_POSTS_REQUEST: return assign({}, state, { [action.subject]: { isFetching: true, state: 'loading', subject: action.subject, response: null, error: null, } } ); case FETCH_POSTS_FAILURE: return assign({}, state, { [action.subject]: { isFetching: false, state: 'error', subject: action.subject, response: state[action.subject].response, error: action.error, } } ); case FETCH_POSTS_SUCCESS: return assign({}, state, { [action.subject]: { isFetching: false, state: 'success', subject: action.subject, response: action.response, } } ); case FETCH_POSTS_CLEAR: return assign({}, state, { [action.subject]: { isFetching: false, state: 'cleared', subject: null, response: null, error: null, } } ); default: return state; }}將請求進行封裝
const request = (subject, model, next) => { _dispatch(fetchPostsRequest(subject, model, next)); return true;};將結果進行封裝
const getResponse = state => state && state.response !== null && state.response;const getLoading = (states = []) => states.reduce((pre, cur) => pre || (cur && cur.isFetching) , false) || false;
使用方法redux-request-async-middleware
四、總結
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點
疑難解答