React中数组调用filter方法报includes is not a function如何解决
错误根因
includes() 是字符串、数组类型自带的方法,你filter遍历得到的currencyInfo是items数组里的单个对象,对象本身没有includes方法,直接调用就会抛出该类型错误。
修复方案
修改filter的判断逻辑,先取对象中需要匹配的productIdentifier字段的字符串值,再调用includes做判断;同时渲染时不能直接输出整个对象,要指定展示的对象属性,示例代码如下:
function ProductList() { var items = [ { "id": 1, "productName": "shoes", "productIdentifier": "CL001", "productDescription": "adidas kicks boir", "productPrice": 2000, "productStock": 200, "created_at": "2020-51-28", "updated_at": null }, { "id": 2, "productName": "burger", "productIdentifier": "FD001", "productDescription": "charsiu berger", "productPrice": 2000, "productStock": 200, "created_at": "2020-51-28", "updated_at": null } ] return ( <> {items.filter(currencyInfo => currencyInfo.productIdentifier.includes("FD001")).map((value, index) => ( <h1 key={index}>{value.productName}</h1> ))} </> ) }
内容的提问来源于stack exchange,提问作者Matt
相关产品推荐
相关产品推荐

