过多if else嵌套/代替switch的写法

作者: 小枫枫

临枫的项目经历分享给你们啦~

扫码交朋友

标签:

特别声明:文章有少部分为网络转载,资源使用一般不提供任何帮助,特殊资源除外,如有侵权请联系!

最近比较忙  菜是原罪 穷也是 每天也要进步一点点   就不整理代码格式了 直接贴代码了

这个是我用于uniApp项目里面请求拦截器里判断响应码执行的操作,由于响应码越来越多一堆if else 看起来头疼 就靠度娘改了写法

先看一下之前的 if else的写法

if (res.code == 200) {
    // res为服务端返回值,可能有code,result等字段
    // 如果配置了originalData为true,请留意这里的返回值
    return res;
} else if (res.code == 201) {
    return res;
} else if (res.code == 406) {
    // 假设406为token失效,这里跳转登录
    // 只能跳转一次
    if (!canLogin) return;
    signOut();
    vm.toast('验证失败,请重新登录');
    setTimeout(() => {
        uni.navigateTo({url: '/pages/login/login'})
    }, 1000);
    canLogin = false;
    return res;
} else if (res.code == 500) {
    vm.toast(res.msg)
    return res;
} else if (res.code == 501) {
    // 501帐号异常 请使用验证码登录
    vm.toast(res.msg)
    return res;
} else if (res.code == 1000) {
    // 加签验证失败
    return res;
} else if (res.code == 1001) {
    // 已创建实人认证订单  代表无需再次支付
    return res;
} else if (res.code == 1002) {
    // 提示App需要版本升级
    return res;
} else {
    return res;
}

这是优化后的写法   嗯?好像更长了  可以继续封装的  下面那个案例看起来整齐一点 

const actions = new Map([
    [200, () => res],
    [201, () => res],
    [406, () => {
        if (!canLogin) return;
        signOut();
        vm.toast('请登录');
        canLogin = false;
        setTimeout(() => {
            uni.navigateTo({
                url: '/pages/login/login'
            })
            canLogin = true;
        }, 1000);
        return res;
    }],
    [500, () => {
        vm.toast(res.msg);
        return res;
    }],
    [501, () => {
        vm.toast(res.msg);
        return res;
    }],
    [1000, () => res],
    [1001, () => res],
    [1002, () => res],
    ['default', () => res]
])
let action = actions.get(res.code) || actions.get('default');
//vue项目比较特殊? 这里要走一个return  平常项目不需要return直接执行action();就可以了  
return action.call(this)

 

下面事例是在平常的项目中的判断使用的 

 

var url = '';
let res = null
init()
// 可以假设  params = {type: "sqjc"}
function init() {
    if (params) {
        // 这是原 switch 进行判断的
        // switch (params.type) {
        //     case 'gxz':
        //         url = './image/gxzimg.png';
        //         document.title = '贡献值规则'
        //         break;
        //     case 'fxz':
        //         url = './image/fxzimg.png';
        //         document.title = '分享值规则'
        //         break;
        //     case 'xjdr':
        //         url = './image/xjdrimg.png';
        //         document.title = '星级达人规则'
        //         break;
        //     case 'hyd':
        //         url = './image/hydimg.png';
        //         document.title = '活跃度规则'
        //         break;
        //     case 'xszn':
        //         document.title = '新手指南'
        //         res = await ajax.post(baseApi, {
        //             type: params.type
        //         });
        //         url = res.data.data.value
        //         break;
        //     case 'sqjc':
        //         document.title = '省钱教程'
        //         res = await ajax.post(baseApi, {
        //             type: params.type
        //         });
        //         url = res.data.data.value
        //         break;
        //     case 'ptkf':
        //         document.title = '平台客服'
        //         res = await ajax.post(baseApi, {
        //             type: params.type
        //         });
        //         url = res.data.data.value
        //         break;
        //     case 'zskf':
        //         document.title = '专属客服'
        //         res = await ajax.post(baseApi, {
        //             type: params.type
        //         });
        //         url = res.data.data.value;
        //         showImg = true;
        //         break;
        //     case 'cjwt':
        //         document.title = '常见问题'
        //         res = await ajax.post(baseApi, {
        //             type: params.type
        //         });
        //         url = '';
        //         document.getElementById("content").innerHTML = res.data.data.value
        //         break;
        //     case 'yhxy':
        //         res = await ajax.post(baseApi, {
        //             type: params.type
        //         });
        //         url = res.data.data.value
        //         document.title = '用户协议'
        //         break;
        //     case 'ystk':
        //         res = await ajax.post(baseApi, {
        //             type: params.type
        //         });
        //         url = res.data.data.value
        //         document.title = '隐私条款'
        //         break;
        //     default:
        //         break;
        // }

        // 整理后的格式  

        const actions = () => {
            // 公共方法
            const Fn1 = (url, title) => {
                document.title = title;
                document.querySelector("#IMG").src = url
            }
            const FnApiImg = async (title, html, imgbool) => {
                document.title = title;
                res = await ajax.post(baseApi, {
                    type: params.type
                });
                if (html) {
                    document.getElementById("content").innerHTML = res.data.data.value
                } else {
                    url = res.data.data.value;
                    if (imgbool) {
                        showImg = imgbool
                    }
                    document.querySelector("#IMG").src = url
                };
            }
            return new Map([
                ['gxz', () => Fn1('./image/gxzimg.png', '贡献值规则')],
                ['fxz', () => Fn1('./image/fxzimg.png', '分享值规则')],
                ['xjdr', () => Fn1('./image/xjdrimg.png', '星级达人规则')],
                ['hyd', () => Fn1('./image/hydimg.png', '活跃度规则')],
                ['xszn', async () => await FnApiImg('新手指南')],
                ['sqjc', async () => await FnApiImg('省钱教程')],
                ['ptkf', async () => await FnApiImg('平台客服')],
                ['zskf', async () => await FnApiImg('专属客服', null, true)],
                ['cjwt', async () => await FnApiImg('常见问题', true)],
                ['yhxy', async () => await FnApiImg('用户协议')],
                ['ysxy', async () => await FnApiImg('隐私协议')],
                ['default', () => {
                    document.getElementById("content").innerHTML = '暂无数据'
                }]
            ])
        }
        //---------假设parmas.type == gxz
        // --------这里的filter内结构了['gxz', () => Fn1('./image/gxzimg.png', '贡献值规则')]    key为'gxz' |  value 为Fn1这个方法
        let action = [...actions()].filter(([key, value]) => (key == (params.type)));
        // 这里的 action 查到了type为gxz的数组那个数组 值为 ["sqjc",async () => await FnApiImg('省钱教程')]
        // 这里 key为'gxz' |  value 为Fn1这个方法  使用call 改变了this指向并调用了Fn1的方法
        action.forEach(([key, value]) => value.call(this));
    }
}

 

 

本文最后更新于2020-9-24,已超过 1 年没有更新,如果文章内容或图片资源失效,请留言反馈,我们会及时处理,谢谢!
分享到:
打赏

作者: 小枫枫, 转载或复制请以 超链接形式 并注明出处 小枫枫不疯喔
原文地址: 《过多if else嵌套/代替switch的写法》 发布于2020-9-24

评论

切换注册

登录

您也可以使用第三方帐号快捷登录

切换登录

注册

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏