在React Native FlatList中过滤数据时遇‘undefined is not a function arr.filter’错误
解决FlatList过滤时出现的
undefined is not a function arr.filter错误 这个错误的核心原因是**custData在某个渲染周期中不是数组类型**,导致无法调用数组的filter方法。虽然你初始状态设了空数组[],但后续通过setCustData更新数据时,可能意外赋值了undefined、null或其他非数组值。
修复步骤:
确保
custData始终为数组
在更新custData的地方(比如接口请求后),强制保证赋值为数组:// 示例接口请求处理 fetch('你的接口地址') .then(res => res.json()) .then(data => { // 若接口返回null/undefined,默认设为空数组 setCustData(Array.isArray(data) ? data : []); }) .catch(() => setCustData([]));或者直接在FlatList的
data属性中做兜底判断:data={Array.isArray(custData) ? custData.filter(...) : []}优化过滤逻辑(可选但更健壮)
原过滤逻辑存在两个小问题:一是返回item而非布尔值(虽然JS会隐式转换,但不够规范);二是未处理item.partyname为undefined的情况。优化后代码:<FlatList data={Array.isArray(custData) ? custData.filter(item => { if (!searchFilter) return true; // 可选链避免partyname不存在时报错,toLowerCase统一大小写 return item.partyname?.toString().toLowerCase().includes(searchFilter.toLowerCase()) || false; }) : []} keyExtractor={({id}, index) => id} renderItem={({item, index}) => ( <Text style={{color: '#ffffff'}}>{item.partyname}</Text> )} />
内容的提问来源于stack exchange,提问作者Khuzaima Amir
相关产品推荐
相关产品推荐

