我有一个可选的平面列表。当用户触摸一行时,它会选择该特定项并将该项ID存储在数组中。但是当我试图通过再次触摸所选项目取消选择项目时,它不会取消选择&再次在数组中添加它,但如果我再次触摸它然后它从数组中删除项目但仍然不取消选择。下面是我的平面列表代码:
import React, {Component} from 'react';
import {
StyleSheet,
Text,
View,
TouchableOpacity,
FlatList,
List,
ListItem
} from 'react-native';
import {
Container,
Header,
Item,
Input,
Button,
StyleProvider,
Icon,
Body,
Right,
StatusBar,
Card,
CardItem,
CheckBox,
Left
} from 'native-base';
export default class UserList extends Component {
constructor(props) {
super(props);
const {params} = this.props.navigation.state;
this.state = {
data: [],
SelectedUserList: params.selectedUserID.slice(),
SelectedUserListName: [],
renderedListData: [],
IsInArray: true,
selectedUserID: params.selectedUserID,
IsSelected: (new Map(): Map<string, boolean>)
}
console.log("selectedUserID" + JSON.stringify(this.state.selectedUserID))
console.log("selectedCropName" + JSON.stringify(params.SelectedUserListName))
}
press = (hey) => {
console.log('Press:'+this.state.SelectedUserList)
this.state.renderedListData.map((item) => {
if (item.id === hey.id) {
item.check = !item.check
if (item.check === true) {
this.state.SelectedUserList.push(item.id);
this.state.SelectedUserListName.push(item.name);
console.log('selected:' + item.name);
console.log(this.state.SelectedUserListName.includes(item.id))
} else if (item.check === false) {
const i = this.state.SelectedUserList.indexOf(item)
const j = this.state.SelectedUserListName.indexOf(item)
if (1 != -1) {
this.state.SelectedUserList.splice(i, 1)
this.state.SelectedUserListName.splice(j, 1)
console.log('unselect:' + item.name)
return this.state.SelectedUserList
}
}
}
})
this.setState({data: this.state.data})
}
componentDidMount() {
//Fetch Data From API
...
}
render() {
return (
<View style={styles.container}>
<View style={styles.storyContainer}>
<FlatList data={this.state.renderedListData} keyExtractor={item => item.id.toString()}
extraData={this.state}
renderItem={({item}) => {
return <TouchableOpacity style={{
flexDirection: 'row',
padding: 2
}} onPress={() => {
this.press(item)
}}>
<View style={{
flex: 3,
alignItems: 'flex-start',
justifyContent: 'center'
}}>
{<Card
style={{
width: '100%',
height: 80,
alignItems: 'center'
}}>
<CardItem style={{height: '100%'}}>
<Left>
<View style={{
flex: 1,
flexDirection: 'row',
alignItems: 'center'
}}>
<CheckBox checked={(this.state.selectedUserID.includes(item.id) || item.check ) ? true : false}
style={{marginRight: 15}}/>
<View>
<Text style={{
color: "#24466B",
fontSize: 16
}}>
{item.name}
</Text>
</View>
</View>
</Left>
</CardItem>
</Card>}
</View>
</TouchableOpacity>
}}/>
</View>
</View>
)
}
};
它将SelectedUserList定义为:
SelectedUserList: params.selectedUserID.slice()
因为当用户选择列表并单击“确定”时,它会将该数组推送到上一个屏幕,如果用户再次尝试重新选择它,则会将数组推送到列表屏幕,之前选择的项目将自动在列表屏幕上重新选择。
onPress之前工作正常但是当我添加了状态切片时,它停止了取消选择。我添加了具有数组状态的切片,因为它设置了在前一个屏幕上的状态
答案 0 :(得分:-1)
在press
中,我猜条件应该是i != -1
而不是1 != -1
。请检查一下。