You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

多条件场景下如何精简页面数据刷新的冗余代码?

精简refresh()方法的方案

可以通过路由规则与操作的映射配置简化代码,把分散的if判断统一成遍历配置数组的逻辑,既精简代码也方便后续维护:

refresh() {
  this.store$.dispatch(setLoadingSpinner({ status: true }));
  this.store$.dispatch(loadCountNotifications());
  this.store$.dispatch(loadCountPostsIsTrue());

  const url = this.route.routerState.snapshot.url;
  // 路由规则与对应操作的映射配置
  const routeActions = [
    {
      match: () => url.includes('/notifications'),
      actions: [() => this.store$.dispatch(loadNotifications({ page: 1, pageSize: 10 }))]
    },
    {
      match: () => url.includes('/organizations') || 
        (url.includes('/requests') && !url.includes('/requests/n/') && !url.includes('/requests/post/')),
      actions: [() => this.store$.dispatch(loadOrgs())]
    },
    {
      match: () => url.includes('/users'),
      actions: [() => this.store$.dispatch(loadUsers())]
    },
    {
      match: () => url.includes('/requests/n/') || 
        (url.includes('/my_requests') && !url.includes('/my_requests/n/')),
      actions: [() => this.store$.dispatch(loadPosts())]
    },
    {
      match: () => url.includes('/requests/post/') || url.includes('/my_requests/n/'),
      actions: [
        () => this.store$.dispatch(loadPosts()),
        () => this.store$.dispatch(loadComments())
      ]
    }
  ];

  // 遍历配置,执行匹配的操作
  routeActions.forEach(item => {
    if (item.match()) {
      item.actions.forEach(action => action());
    }
  });
}

优化说明

  • 提前提取路由URL为变量,避免重复调用this.route.routerState.snapshot.url
  • 用数组统一管理所有路由匹配规则和对应dispatch操作,逻辑更集中清晰
  • 合并了重复的操作逻辑(比如多处需要触发loadOrgs、loadPosts的条件)
  • 后续新增或修改路由规则时,只需在routeActions数组中调整元素,无需改动核心遍历逻辑

内容的提问来源于stack exchange,提问作者user19639900

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 17:06:32