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

React Native中FlatList移除对象时出现"undefined is not an object (evaluating 'List.filter')"错误的问题求助

问题排查与解决方案

错误原因分析

你遇到的undefined is not an object (evaluating 'List.filter')错误,核心有两个关键问题:

  1. removeItem函数的参数未正确传递:你调用this.removeItem时没有传入任何参数,导致函数里的List变量是undefined,自然无法调用filter方法。
  2. 缺少目标删除项的标识:就算传了List,item.key !== key里的key也没有对应的值,代码不知道要过滤掉哪一项。

另外,你的删除逻辑没有关联到当前长按的具体列表项,弹窗确认后无法定位要删除的对象,这也是导致问题的重要原因。

分步解决方案

1. 修改弹窗函数,支持接收当前要删除的item

把openTwoButtonAlert改成可以接收当前item的函数,让弹窗的确认按钮能拿到要删除项的唯一标识:

openTwoButtonAlert = (item) => {
  Alert.alert(
    'Delete List',
    'Are you sure to delete this list?',
    [
      {text: 'Delete', onPress: () => this.removeItem(item.key)},
      {text: 'Cancel', style: 'cancel'},
    ],
  );
}

2. 修复removeItem函数逻辑

直接从组件状态里取列表数据,用传入的目标key来过滤,不用依赖外部传List:

removeItem = (targetKey) => {
  // 从当前state中获取列表,过滤掉key等于targetKey的项
  let filteredItems = this.state.List.filter(item => item.key !== targetKey);
  this.setState({ List: filteredItems });
}

3. 调整FlatList的renderItem,传递当前item给长按事件

在FlatList的TouchableOpacity里,把当前渲染的item传给openTwoButtonAlert,让长按事件知道要操作哪一项:

<FlatList 
  data={this.state.List} 
  keyExtractor={(item, index) => item.key.toString()} 
  renderItem={({ item }) => ( 
    <TouchableOpacity onLongPress={() => this.openTwoButtonAlert(item)}>
      {/* 这里可以添加你的列表项内容,比如显示名称或其他属性 */}
      <Text>{item.Name || 'Unnamed Item'}</Text>
    </TouchableOpacity>
  )} 
/>

4. 额外优化:避免getDerivedStateFromProps重复添加数据

当前的getDerivedStateFromProps每次只要props.route.params?.list存在,就会往List里加新项,这可能导致重复添加(比如从详情页返回多次时)。可以添加判断,确保只添加不存在的项:

static getDerivedStateFromProps(props, state) {
  const newItem = props.route.params?.list;
  if (newItem && !state.List.some(item => item.key === newItem.key)) {
    return { 
      List: [...state.List, newItem], 
    };
  }
  return null;
}

验证修改后的流程

  1. 长按列表项时,弹窗会获取当前item的唯一key;
  2. 点击Delete后,removeItem会用该key过滤掉对应项并更新state;
  3. FlatList会自动重新渲染,展示删除后的最新列表。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 21:12:34