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

React项目中getCategoryNameById函数匹配分类ID总返回none问题

错误原因

你在Product组件中错误遍历了父组件传入的全局分类对象数组props.cate,将完整的分类对象作为参数传入getCategoryNameById函数,函数内拿分类ID和完整对象比对永远无法匹配,所以固定返回none。你原本应该遍历每个产品自身存储的分类ID数组,再将ID传入函数匹配名称。

修复方案

1. 修正Product组件的遍历逻辑

先遍历产品列表,再遍历单个产品的categories分类ID数组:

{
  // 遍历所有产品
  props.products.map(product => (
    <View key={product.id}>
      {/* 产品名称、图片等原有渲染逻辑 */}
      {
        // 遍历当前产品的分类ID数组
        product.categories.map(categoryId => (
          <View 
            key={categoryId}
            style={{ flexDirection:'row' }}
          >
            <Text style={{ ...FONTS.body3 }}>
              {props.function(categoryId)}
            </Text>
            <Text>.</Text>
          </View>
        ))
      }
    </View>
  ))
}

2. 可选优化:简化匹配函数

用find代替filter减少不必要的遍历,同时用严格相等避免类型匹配问题:

function getCategoryNameById(id) {
  // 可根据实际情况做类型转换,比如 id = Number(id) 避免数字和字符串匹配失败
  const category = categories.find(item => item.id === id)
  return category ? category.name : "none"
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 12:24:07