我在页面上显示项目列表,我为用户提供了删除功能。当用户点击删除时,使用我的代码,我收到此错误
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>
如何使其工作,以便它可以删除要使用要从数组中删除的特定行?
你需要在构造函数中将handleExistGroup()函数与this
绑定。
constructor(props) {
super(props);
this.handleExistGroup = this.handleExistGroup.bind(this);
}