I do not know if this is possible, but I am trying to store persistent data in async storage, so whenever the array data in the storage key is fetched, that persistent data is always at the top of the array.
(我不知道这是否可行,但是我试图将持久性数据存储在异步存储中,因此,每当获取存储密钥中的数组数据时,该持久性数据始终位于数组的顶部。)
Also, persistent data cannot be deleted.(同样,不能删除持久数据。)
below is a sample code, and I have shown only the functions for better clarity.(下面是一个示例代码,为了更好地说明,我仅显示了这些功能。)
componentWillMount() {
this.saveData();
}
componentDidMount() {
this.getDataSync();
}
getDataSync = async () => {
try {
const list = await AsyncStorage.getItem(LIST_STORAGE_KEY);
const parsedList = JSON.parse(list);
this.setState({
isDataReady: true,
list: parsedList || []
});
console.log(parsedList, this.state.list);
} catch (e) {
Alert.alert('Failed to load list.');
}
}
saveData = () => {
const data = [
{
firstname: 'John',
lastname: 'Doe',
image: null,
email: 'john@doe.com',
key: 0,
phone: '19191919191',
},
];
this.setState(
prevState => ({
list: [data, ...prevState.list]
}),
() => this.saveItems(this.state.list)
);
}
handleDelete(item) {
if (item.key === 0) {
Alert.alert('You cannot delete this user');
} else {
this.setState(({ list }) => ({
list: list.filter(o => o.key !== item.key)
}),
() => this.saveItems(this.state.list)
);
console.log('deleted: ', item);
}
}
handleAdd() {
const { firstname, lastname, email, phone } = this.state;
const ID = uuid();
const newItemObject = {
key: ID,
firstname: firstname,
lastname: lastname,
email: email,
phone: phone,
image: null,
};
this.setState(
prevState => ({
list: [...prevState.list, newItemObject]
}),
() => this.saveItems(this.state.list)
);
}
saveItems = list => {
AsyncStorage.setItem(LIST_STORAGE_KEY, JSON.stringify(list));
};
ask by vincent O translate from so
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…