时间:2022-05-29 09:30:13 | 栏目:JavaScript代码 | 点击:次
一、redux基础
redux
react-redux
二、redux处理异步的中间件
redux-thunk
redux-saga
三、redux-request-async-middleware
先从redux文档中的异步action说起,每个接口调用需要dispatch三个同步action,分别是:
也就是一个接口发起是这样的
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
四、总结