我不知道这是否可行,但是我试图将持久性数据存储在异步存储中,因此,每当获取存储密钥中的数组数据时,该持久性数据始终位于数组的顶部。同样,不能删除持久数据。下面是一个示例代码,为了更加清晰,我仅显示了这些功能。
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));
};
答案 0 :(得分:0)
向对象添加另一个属性,您不想将其删除。 Asyncstorage默认是持久的。
{
firstname: 'John',
lastname: 'Doe',
image: null,
email: 'john@doe.com',
key: 0,
phone: '19191919191',
delete: false, // won't be deleted
},
在您的getDataSync
中,按delete
属性对列表进行排序。
getDataSync = async () => {
try {
const list = await AsyncStorage.getItem(LIST_STORAGE_KEY);
const parsedList = JSON.parse(list);
// items with .delete property set to false, will be at the top of the list
parsedList.sort((x, y) => (x.delete === y.delete ) ? 0 : x ? 1 : -1);
this.setState({
isDataReady: true,
list: parsedList || []
});
console.log(parsedList, this.state.list);
} catch (e) {
Alert.alert('Failed to load list.');
}
}