代码优化

描述:不同的请求接口,不同的code权限码,不能的type类型,相同的处理逻辑,后端配合几个接口数据返回格式名称一致

解决:采用配置项的形式,写一套逻辑代码,简化代码

getSelectData = () => {
    
      const selectDataArr = [
             {
                 service:aService.A,
                 authCode:auth.a,
                 type:'a',
              }, 
              {
                 service:bService.B,
                 authCode:auth.b,
                 type:'b',
              }, 
             {
                 service:cService.C,
                 authCode:auth.c,
                 type:'c',
               }, 
        ];
        selectDataArr.map(item => {
             item.service(
                  // 传参
                 {
                    status:item.type='a'?'a':'',
                     authCode:item.authCode
                  }
             ).then(res => {
                 if(res.items){
                     // 获取后台数据后的处理,这里要求后台几个接口返回数据格式名称一致
                     this.setState({ 
                         [item.type]:res.items || []; 
                      })
                 }
             }).catch(err => {
                   // 捕获错误处理  
             })
        })       
}        

描述:过滤掉数组中为null元素,防止占位符:

解决:filter, 不会改变原始数组,返回新数组

arr = arr.filter(item => item !== null )

描述:同一个按钮,不同角色登录点击时处理不同情况,如门店a登录点击按钮导出a流水数据,门店b登录点击导出b营业数据

解决:当前页面url可以获取角色或者登录返回获取角色,根据角色判断查询的接口及传参处理,统一接口调用及返回处理  

handleCommon = () => {
      const { location } = this.props.history;
      const currentUrl = location.pathname;
      const isA = currentUrl == 'aaa';
      const isB = currrentUrl == 'bb';
      const params;
      if(){} // 条件判断拦截
      if(isA){
         // params、fileNameExport、 serviceCommon处理
      } else if(isB){
        // params、fileNameExport、 serviceCommon处理
      }else{
        // params、 serviceCommon处理
      } 
      serviceCommon({ ...params}).then(res => {
             const content = res; // 返回的内容
             const fileName = fileNameExport; // 下载文件名
             this.download(content, fileName);
    });
}

 // 处理下载流
download = (content, fileName) => {
    const blob = new Blob([content]);
   // 创建一个类文件对象:Blob对象表示一个不可变的、原始数据的类文件对象
    const url = window.URL.createObjectURL(blob); 
   // URL.createObjectURL(object)表示生成一个File对象或Blob对象
    const dom = document.createElement('a');
   // 设置一个隐藏的a标签,href为输出流,设置download
    dom.style.display = 'none';
    dom.href = url;
    dom.setAttribute('download', fileName);
    // 指示浏览器下载url,而不是导航到它;因此将提示用户将其保存为本地文件
    document.body.appendChild(dom);
    dom.click();
  };

描述:共用组件页面,有些元素根据条件存在,根据条件代表不同的数据

解决:元素权限,绑定后端权限码前端自动显示隐藏或者根据角色前端控制显示隐藏,控制不同的含义  

  

原文地址:https://www.cnblogs.com/haimengqingyuan/p/14201673.html