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

React过滤数组报错TypeError: includes is not a function求助

解决React中TypeError: includes is not a function的问题

你碰到的这个报错很典型——includes()是字符串专属方法,如果你的record.id是数字类型(比如后端返回的ID是整数),直接调用它肯定会抛出includes is not a function的错误。

从你的代码来看,构造函数里state.id被初始化为空字符串'',但通过axios.get获取的records里,record.id大概率是数字格式(后端接口常见的设计),类型不匹配就触发了这个问题。

给你几个简单的解决思路:

1. 把record.id转为字符串后再调用includes

这是最直接的前端处理方式,不管后端返回的id是数字还是字符串,转成字符串后都能正常使用includes做模糊匹配:

this.state.records.filter(record => 
  this.state.id == '' || record.id.toString().includes(this.state.id)
).map(record=> ( 
  <ProjectItem key={record.id} project={record} /> 
))

2. 验证record.id的类型(排查用)

如果不确定record.id到底是什么类型,可以在filter里加个日志确认:

this.state.records.filter(record => {
  console.log('record.id类型:', typeof record.id); // 控制台会输出number或string
  return this.state.id == '' || record.id.toString().includes(this.state.id)
})

3. (可选)统一state中id的类型

如果你的业务里id本来就应该是数字,也可以把state.id转为数字后做判断,但因为你用的是模糊匹配(includes),这种场景下转字符串还是更合适。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 13:52:45