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

JavaScript ES6如何优化React项目中的多层if-else判断函数?

优化方案

方案1:配置化映射 + 数组查找(最推荐)

将断点和对应返回值抽成独立的有序配置数组,用Array.find匹配符合条件的项,完全消除if-else嵌套:

// 断点按从小到大排序,保证匹配优先级和原有if-else逻辑完全一致
const WIDTH_BREAKPOINTS = [
  { threshold: responsiveWidth.phone, perPage: 1 },
  { threshold: responsiveWidth.tablet, perPage: 2 },
  { threshold: responsiveWidth.smallDesktop, perPage: 3 },
  { threshold: responsiveWidth.desktop, perPage: 4 },
]

const calc = () => {
  const matched = WIDTH_BREAKPOINTS.find(item => 100 < item.threshold)
  setPerPage(matched ? matched.perPage : 6)
}

该方案优势:

  • 配置与逻辑完全分离,后续新增/修改断点、调整对应页数只需修改WIDTH_BREAKPOINTS数组,无需改动核心计算逻辑
  • 代码可读性高,所有断点规则一目了然
  • 可进一步抽离为公共常量/工具函数,全局复用

方案2:对象映射表(适合需要保留设备类型判断的场景)

如果需要同时获取当前匹配的设备类型,可将映射关系存在对象中,仅保留判断设备类型的逻辑,赋值逻辑统一抽离:

const PER_PAGE_MAP = {
  phone: 1,
  tablet: 2,
  smallDesktop: 3,
  desktop: 4,
  fallback: 6
}

const calc = () => {
  let device = 'fallback'
  if (100 < responsiveWidth.phone) device = 'phone'
  else if (100 < responsiveWidth.tablet) device = 'tablet'
  else if (100 < responsiveWidth.smallDesktop) device = 'smallDesktop'
  else if (100 < responsiveWidth.desktop) device = 'desktop'
  setPerPage(PER_PAGE_MAP[device])
}

进阶优化

如果判断的宽度值是动态的,可以把计算逻辑封装成通用工具函数,提升复用性:

const getPerPageByWidth = (checkWidth) => {
  const matched = WIDTH_BREAKPOINTS.find(item => checkWidth < item.threshold)
  return matched ? matched.perPage : 6
}

// 调用示例
setPerPage(getPerPageByWidth(100))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 08:15:02