最近公司让用react写一个钉钉的微应用APP 而后就只能去学了react, 以前一直用angular和vue, 因此异步请求用的都是jquery和axios, 想转来转去麻烦 就直接用了axios, 而后网上找了一下 竟然有axios的redux中间件vue
一开始使用axios, 由于没有finally方法,写起来老是有点别扭 因此引入了q.js 须要把请求都用Q.Promise封装一遍,像这样react
//定义 export function getUserInfo() { return Q.Promise((success, error) => { axios.post('[url]').then(function (data) { if (data.code == 200) { success(data.data) } else { error() } }).catch(function (err) { error() }); }) } //使用 getUserInfo() .then(()=>{ }) .catch(()=>{ }) .finally(()=>{ })
最后在看 axios的issues的时候无心间看到有人提问 能够用这个库 实现对es6promise的扩展 以后就很简单了jquery
//只要引入这个模块 使用下这个方法就搞定了 require('promise.prototype.finally').shim() //使用 axios.post('[url]') .then((data)=> { }) .catch((err)=> { }) .finally(()=> { })
咱们作业务的时候确定会有 loading 这个变量,在请求前须要让加载框出现,在完成后须要隐藏
不对redux-axios-middleware进行配置的话是这样的,能够看到 写了2遍state.setIn(['obj', 'loading'], false);
ios
case 'GET_CATEGORY_LIST': return state.setIn(['obj', 'loading'], true); break; case 'GET_CATEGORY_LIST_SUCCESS': state = state.setIn(['obj', 'list'], fromJS(aciton.payload.data)) return state.setIn(['obj', 'loading'], false); break; case 'GET_CATEGORY_LIST_FAIL': return state.setIn(['obj', 'loading'], false); break;
看了下源码 他是有一个onComplete
方法能够定义的,方式以下git
#axiosMiddlewareOptions.js import { getActionTypes } from 'redux-axios-middleware/lib/getActionTypes' export const returnRejectedPromiseOnError = true; export const onComplete = ( { action, next, getState, dispatch }, actionOptions) => { const previousAction = action.meta.previousAction; const nextAction = { type: getActionTypes(previousAction, actionOptions)[0]+'_COMPLETE', meta: { previousAction: previousAction } }; next(nextAction); return nextAction; };
#store.js import { createStore, compose, applyMiddleware } from 'redux' import axios from 'axios'; import axiosMiddleware from 'redux-axios-middleware'; import * as axiosMiddlewareOptions from './common/axiosMiddlewareOptions' const enhancers = compose( applyMiddleware( axiosMiddleware(axios, {...axiosMiddlewareOptions}), //axios 中间件 ), window.devToolsExtension ? window.devToolsExtension() : f=>f );
这样配置完以后,axios中间件每次请求完 都会执行一个[type]_COMPLETE
的action,上面的reducer能够优化为(若是为错误不处理的话,通常都会在axios的interceptors里作)es6
case 'GET_CATEGORY_LIST': return state.setIn(['obj', 'loading'], true); break; case 'GET_CATEGORY_LIST_SUCCESS': return state.setIn(['obj', 'list'], fromJS(aciton.payload.data)) break; case 'GET_CATEGORY_LIST_COMPLETE': return state.setIn(['obj', 'loading'], false); break;
上面还有一个配置export const returnRejectedPromiseOnError = true;
他的做用是让axios中间件请求出错的时候走catch方法,能够是代码结构更清晰。github
#redux-axios-middleware 源码 return actionOptions.returnRejectedPromiseOnError ? Promise.reject(newAction) : newAction;
而后就可使用axios中间件请求更爽的写业务代码啦,上面说的是在 redux 中的数据,下面这个是如何更好控制在state中的数据,下面的3个方法实际上是axios.request()的方法,因为咱们使用第2种方法给promise添加了finally方法,因此如今能够这样使用它redux
this.setState({ refreshing: true }); this.props.userHome() .then(()=>{ }) .catch(()=>{ }) .finally(()=>{ this.setState({ refreshing: false }); })
ok 搞完了axios