繁体   English   中英

从 Flatlist 中移除对象时,undefined 不是对象(评估“this.setState”)

[英]undefined is not an object (evaluating 'this.setState') when Removing object from Flatlist

因此,我目前正在 React Native 中学习 Flatlists,并且我正在尝试编写一个函数,通过在按钮中使用 onLongPress 来删除 Flatlist 中的项目,这是终端中显示的项目示例:

Array [
  Object {
    "Friday": false,
    "Monday": true,
    "Saturday": false,
    "Sunday": false,
    "Thursday": false,
    "Tuesday": false,
    "Wednesday": false,
    "key": 0.08631781113770953,
    "workoutName": "",
  },
]

这是我正在使用的功能,我按照教程获得:

removeItem(item){
    this.setState({
       workoutList: this.state.workoutList.filter((item)=>item.key !== item.key)
    });
}

这是我调用函数的地方:

openTwoButtonAlert = () => {
    Alert.alert(
       'Delete Workout',
      'Are you sure to delete this Workout?',
      [
        {text: 'Delete', onPress: this.removeItem(item)},

        {text: 'Cancel', 
           style: 'cancel',
           
        },
      ],
    );
  }

这是我的长笛演奏家:

 <FlatList
              data={this.state.workoutList}
              keyExtractor={(item, index) => item.toString()}
              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>
              )}
            />

要更新的状态是锻炼列表,我正在使用类组件,当我启动代码时,它返回错误: TypeError: undefined is not an object (evaluating 'this.setState')在此先感谢您的帮助。

试试这个方法(更新)

<FlatList
   ...
    keyExtractor={(item, index) => item.toString()} // update here also
    renderItem={({item, index}) => ( // **** updated here ****
       .....
       onLongPress={() => this.openTwoButtonAlert(index)}
       ...
    )
   ... 
/>

openTwoButtonAlert = (index) => { // updated here
    Alert.alert(
      ...
        {text: 'Delete', onPress: () => this.removeItem(index)}, // change here
      ...
    );
}

removeItem(index){
    // updated code of removing item from list
    const newData = [...this.state.workoutList]; // this code is making clone of the data list
    newData.splice(index, 1); // remove item from list
    this.setState({workoutList: newData}); // reset data to list       
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM