给 axios 和 redux-axios-middleware 添加finally方法 的使用心得

发布时间:2019-08-11 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了给 axios 和 redux-axios-middleware 添加finally方法 的使用心得脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

最近公司让用react写一个钉钉的微应用APP 然后就只能去学了react, 之前一直用Angular和vue, 所以异步请求用的都是jquery和axios, 想转来转去麻烦 就直接用了axios, 然后网上找了一下 居然有axios的redux中间件

axios 实现finally方法

实现方式1 - q.js

开始使用axios, 因为没有finally方法,写起来总是有点别扭 所以引入了q.js 需要把请求都用Q.Promise封装一遍,像这样

//定义
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(()=>{
    })

实现方式2 - PRomise.prototype.finally

最后在看 axios的issues的时候无意间看到有人提问 可以用这个库 实现对es6promise的扩展 之后就很简单

//只要引入这个模块 使用下这个方法就搞定require('promise.prototyPE.finally').shim() 


//使用
axios.post('[url]')
    .then((data)=> {
    })
    .catch((err)=> {
    })
    .finally(()=> {
    })

redux-axios-middleware 实现finally方法

我们做业务的时候肯定会有 loading 这个变量,在请求前需要让加载框出现,在完成后需要隐藏
不对redux-axios-middleware进行配置的话是这样的,可以看到 写了2遍state.setIn(['obj', 'loading'], @L_304_13@);

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;

对redux-axios-middleware进行配置

看了下码 他是有一个onComplete 方法可以定义的,方式如下

#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里做)

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方法,可以是代码结构更清晰。

#redux-axios-middleware 源码
return actionOptions.returnRejectedPromiseOnError ? Promise.reject(newAction) : newAction;

然后就可以使用axios中间件请求更爽的写业务代码啦,上面说的是在 redux 中的数据,下面这个是如何更好控制在state中的数据,下面的3个方法其实是axios.request()的方法,由于我们使用第2种方法给promise添加了finally方法,所以现在可以这样使用它

this.setState({ refreshing: true });
this.props.userHome()
    .then(()=>{
        
    })
    .catch(()=>{
    })
    .finally(()=>{
        this.setState({ refreshing: false });
    })

ok 搞完了

脚本宝典总结

以上是脚本宝典为你收集整理的给 axios 和 redux-axios-middleware 添加finally方法 的使用心得全部内容,希望文章能够帮你解决给 axios 和 redux-axios-middleware 添加finally方法 的使用心得所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。