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

使用.find()渲染数组单条数据时返回undefined问题排查

问题分析与解决

核心问题是类型不匹配:

  • useParams()获取到的id是字符串类型
  • 你定义的services数组中,每个对象的id是数字类型

用===做全等比较时,字符串和数字永远不相等,所以find()找不到匹配的对象,返回undefined。

解决方法

推荐将字符串类型的id转为数字后再比较,类型一致后匹配逻辑就能正常工作:

const { id } = useParams();
// 方法1:用Number()转换
const service = services.find((item) => item.id === Number(id));

// 或者方法2:用+号快速转数字
// const service = services.find((item) => item.id === +id);

如果不想做类型转换,也可以用松散相等==(不推荐,隐式转换可能带来潜在问题):

const service = services.find((item) => item.id == id);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 18:54:53