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

在React Native FlatList中过滤数据时遇‘undefined is not a function arr.filter’错误

解决FlatList过滤时出现的undefined is not a function arr.filter错误

这个错误的核心原因是**custData在某个渲染周期中不是数组类型**,导致无法调用数组的filter方法。虽然你初始状态设了空数组[],但后续通过setCustData更新数据时,可能意外赋值了undefined、null或其他非数组值。

修复步骤:

  1. 确保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(...) : []}
    
  2. 优化过滤逻辑(可选但更健壮)
    原过滤逻辑存在两个小问题:一是返回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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 00:25:20