一、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
四、总结
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持呐喊教程。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。