You need to enable JavaScript to run this app. React Native删除Flatlist项时报undefined is not an object (evaluating 'this.setState')错误
优惠活动
大模型
产品
解决方案
定价
更多

React Native删除Flatlist项时报undefined is not an object (evaluating 'this.setState')错误

React Native FlatList长按删除功能修复方案

核心报错原因及所有逻辑问题梳理

  • this.setState未定义:你声明的removeItem是普通类方法,默认this不会绑定到组件实例,无法访问组件的state和setState方法
  • 参数传递逻辑错误:你在onLongPress中给openTwoButtonAlert传了当前项的index,但该函数没有定义形参接收,也没有把对应标识传给removeItem
  • 过滤逻辑完全失效:removeItem中filter回调的形参和外层入参重名,导致item.key !== item.key永远为false,永远删不掉任何数据
  • Alert按钮触发逻辑错误:Delete按钮的onPress直接执行了removeItem方法,不是传函数引用,会出现弹窗刚弹出就自动执行删除的问题
  • FlatList key提取规则错误:keyExtractor用item.toString()会返回[object Object],所有项key重复,渲染会出问题

完整修改代码

1. 修改removeItem方法(改用箭头函数绑定this,修正过滤逻辑)

// 直接用index过滤更简单,也可以替换为用item的唯一key字段过滤
removeItem = (targetIndex) => {
    // setState使用函数式写法,确保拿到最新的workoutList状态,避免异步更新异常
    this.setState(prevState => ({
       workoutList: prevState.workoutList.filter((_, index) => index !== targetIndex)
    }));
}

2. 修改openTwoButtonAlert方法(接收参数,修正按钮触发逻辑)

// 新增形参接收长按传入的目标项index
openTwoButtonAlert = (targetIndex) => {
    Alert.alert(
       'Delete Workout',
      'Are you sure to delete this Workout?',
      [
        {
          text: 'Delete', 
          onPress: () => this.removeItem(targetIndex) // 改为箭头函数,点击按钮时才执行删除
        },
        {
          text: 'Cancel', 
          style: 'cancel'
        },
      ],
    );
  }

3. 修改FlatList的keyExtractor属性

<FlatList
  data={this.state.workoutList}
  keyExtractor={(item) => String(item.key)} // 用每条数据自带的唯一key字段提取key
  renderItem={({ index, item}) => (
    <View style={{padding:20}}>
      <TouchableOpacity 
        onPress={() => this.props.navigation.navigate("WorkoutCreated", {
          workoutName: item.workoutName,
          Monday: item.Monday,
          Tuesday: item.Tuesday,
          Wednesday: item.Wednesday,
          Thursday: item.Thursday,
          Friday: item.Friday,
          Saturday: item.Saturday,
          Sunday: item.Sunday,
        })} 
        onLongPress={()=>this.openTwoButtonAlert(index)}
      >
        <Text>{item.workoutName}</Text>       
      </TouchableOpacity>
    </View>
  )}
/>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 00:30:05