我试图弄清楚如何在不同的时间将选定的用户添加到多维数组。我的代码现在的工作方式是,它从CustomerQue页面中获取选定的用户,并将其添加到Tables页面中。然后,使用者添加一个表号,然后命中集合,然后将用户添加到该表号。该表是数组。但是当我返回并尝试添加/选择更多用户以添加到其他表时。它将表和用户一起添加。
这是我来自CustomerQue的代码...
constructor(props){
super(props);
this.state = {
rlocationcode: '',
dataSource: [],
selectedUsers: [],
};
}
handleTouchItem2 = async (item) => {
try {
let users = this.state.dataSource;
await AsyncStorage.setItem('users', JSON.stringify(users));
this.props.navigation.navigate("Tables", {
cust_ID: item,
otherParam: '101',
});
} catch (error) {
console.log('There is no one checked in', error.message);
}
}
_didSelectUsers = (item) => {
let selectedUsers1 = this.state.selectedUsers;
let isItemSelected = selectedUsers1.filter(item => {
return item.includes(item);
}).length > 20
? true : false;
if (isItemSelected) {
const index = selectedUsers1.findIndex(
obj => obj.item === selectedUsers1
);
selectedUsers1.splice(index, 1);
} else {
selectedUsers1.push(item);
}
this.setState({ selectedUsers1 });
console.log(selectedUsers1)
}
这是我的表格页面代码。...
constructor(props) {
super(props);
this.array = [],
this.party = [],
this.state = {
arrayHolder: [],
party: [],
disabled: true,
textInput_Holder: '',
selectedIndex: 2,
}
this.updateIndex = this.updateIndex.bind(this)
}
_addTable = (index) => {
if (index === 0) {
this.array.push({Table : this.state.textInput_Holder});
for (var i = 0; i < this.array.length; i++) {
this.setState({ arrayHolder: [...this.array] });
console.log(this.array);
}
}
}
_setTable2 = async (index) => {
if (index === 1) {
const { navigation } = this.props;
const cust = navigation.getParam('cust_ID', 'No-User');
const other_param = navigation.getParam('otherParam', 'No-User');
const cust1 = JSON.stringify(cust);
const cust2 = cust1.replace(/[\])}[{(]/g, '');
const cust3 = cust2.replace(/[""]/g, '');
try {
await AsyncStorage.setItem('cust3', cust3)
let Tab = [this.array];
let TAC = Tab.concat([cust3]);
this.state.party.push([cust3]);
for (var i = 0; i < this.state.party.length; i++) {
this.setState({ party: [...this.state.party]})
console.log(this.state.party.join('\r\n'));
return this.state.party.join('\r\n');
}
} catch(error) {
console.log('There is a problem', error.message);
}
}
}
_openTable = async () => {
try {
const partyGroup = await AsyncStorage.getItem('cust3');
this.props.navigation.navigate('ViewParty', {
TAC1: partyGroup,
otherParam: '101',
});
} catch(error) {
console.log('No Table', error.message)
}
}
我已经尝试从AsyncStorage移除removeItem,它甚至删除了我已经添加到阵列中的所有内容。我试图拼接selectedUsers,它也做同样的事情。它会删除所有内容,当我尝试选择新用户时,会将刚删除的用户添加回所选用户。
处理此问题的最佳方法是什么?
尝试使用本机钩子。或者,您也可以尝试使用状态管理(例如redux mobx)来处理应用程序整个生命周期中的数据。