从本机列表中删除项目

时间:2019-01-28 14:14:56

标签: react-native

我正在页面上显示项目列表,我为用户提供了删除功能。 使用我的代码,当用户点击删除时,我会收到此错误

undefined is not an object (evaluating this.state.myGroups)

JS

handleExistGroup(item) {
  var array = [...this.state.myGroups];
  var index = array.indexOf(item.target.value)
  if (index !== -1) {
    array.splice(index, 1);
    this.setState({myGroups: array});
  }
}

数组

state = {
  myGroups : [
    {
    name: 'Karate Group',
    description: 'Test Group',
    icon: 'https://s3.amazonaws.com/uifaces/faces/twitter/brynn/128.jpg'
  },
    {
      name: 'Choir Group',
      description: 'Test 2',
     icon: 'https://s3.amazonaws.com/uifaces/faces/twitter/brynn/128.jpg'
    }
  ]
}

查看

<View style={styles.container}>
<ScrollView >
  {
    groupList.map((item, i) => {
  return (
  <View key={i} style={styles.user}>
  <Card >
   <ListItem
    roundAvatar
    title={item.name}
    avatar={{uri:'https://s3.amazonaws.com/uifaces/faces/twitter/brynn/128.jpg'}}
    />
<View>
  <Button
   containerViewStyle={{width:'50%', alignSelf:'flex-end', position:"absolute", top:0, right:-25}}
    onPress={()=>(handleExistGroup(item))}
    rounded = {true}
    style={{margin:10}}
    icon={{name: 'trash'}}
    backgroundColor='#DC143C'
    buttonStyle={{borderRadius: 0, marginLeft: 0, marginRight: 0, marginBottom: 0}}
    title='Exit Group' 
  />
</View>


  <Text style={{alignSelf:'center', padding:5, fontFamily:'HelveticaNeue-Light', fontSize:16}}>
  Jonied: 24th January, 2019
  </Text>
    </Card>
  </View>
      );
    })
  }
</ScrollView>
</View>

我如何使其起作用,以便它可以删除用户要从阵列中删除的特定行?

1 个答案:

答案 0 :(得分:1)

您需要在构造函数中将handleExistGroup()函数与this绑定。

constructor(props) {
    super(props);
    this.handleExistGroup = this.handleExistGroup.bind(this);
}