【发布时间】:2020-04-20 03:31:05
【问题描述】:
我正在尝试以本机反应将数据推送到本地存储中,在这种情况下推送多个元素。我正在尝试使用此处指出的文档:
How do I set multiple values within Asyncstorage
我将如何正确地做到这一点?下面是一些代码:
我目前在做什么
const STORAGE_KEY = '@save_enableauto';
const DBLTIME_KEY = '@save_dbltime';
state={
times: Times,
messageTimes: {
dblTime: '12:00 pm',
genTime: '12:00 pm'
}
enableAuto:false
}
//retrieves automatic messaging status
_retrieveData = async () => {
try {
//pull data from local storage
const enableAuto = await AsyncStorage.getItem(STORAGE_KEY);
const dblTime = await AsyncStorage.getItem(DBLTIME_KEY);
console.log('auto messages set: ',enableAuto);
console.log('time data is:', dblTime);
//reset state for time if it exists in local storage
if(dblTime !==null) {
this.setState(prevState => ({
messageTimes: { // object that we want to update
...prevState.messageTimes, // keep all other key-value pairs
dblTime: dblTime // update the value of specific key
}
}))
}
//reset state for notifications if exists in local storage
if (enableAuto !== null) {
// We have data!!
console.log('receiving from local storage: ',enableAuto);
this.setState({ enableAuto:eval(enableAuto) });
}
} catch (error) {
alert('failed to load previous settings.')
// Error retrieving data
}
};
//trying to set it up with one call
_retrieveDataGroup = async () => {
const items = JSON.stringify([['k1', STORAGE_KEY], ['k2', DBLTIME_KEY]]);
try {
const localData = AsyncStorage.multiGet(items, () => {
//to do something
});
console.log('Group fetch: ',localData);
} catch (error) {
alert('failed to load previous settings.')
// Error retrieving data
}
};
现在我收到控制台日志记录组获取是一个承诺:
Group fetch: Promise {
"_40": 0,
"_55": null,
"_65": 0,
"_72": null,
}
【问题讨论】:
标签: javascript reactjs react-native local-storage